MapsActivity.kt 18.6 KB
Newer Older
1 2 3
package com.example.ayudapy

import android.Manifest
4
import android.content.Entity
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
import android.content.Intent
import android.content.pm.PackageManager
import android.location.Location
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.ContactsContract
import android.util.Log
import android.view.View
import android.widget.Button
import android.widget.Toast
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.google.android.gms.location.FusedLocationProviderClient
import com.google.android.gms.location.LocationServices
import com.google.android.gms.maps.CameraUpdateFactory
import com.google.android.gms.maps.GoogleMap
import com.google.android.gms.maps.OnMapReadyCallback
import com.google.android.gms.maps.SupportMapFragment
import com.google.android.gms.maps.model.BitmapDescriptorFactory
import com.google.android.gms.maps.model.LatLng
import com.google.android.gms.maps.model.Marker
import com.google.android.gms.maps.model.MarkerOptions
import com.google.android.material.bottomsheet.BottomSheetDialog
import kotlinx.android.synthetic.main.alert_dialog_contacto.view.*
import kotlinx.android.synthetic.main.fragment_pedido.view.*
34
import kotlinx.android.synthetic.main.info.*
Yannine Alvarez committed
35
import org.jetbrains.anko.doAsync
36 37 38 39 40 41
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter

Yannine Alvarez committed
42

43 44 45 46 47 48 49 50
class MapsActivity : AppCompatActivity(), OnMapReadyCallback, GoogleMap.OnMarkerClickListener {

    private lateinit var mMap: GoogleMap
    private lateinit var lastLocation: Location
    private lateinit var fusedLocationClient: FusedLocationProviderClient
    internal lateinit var infoButton: Button
    private var selectedMarker:Marker?=null

Yannine Alvarez committed
51 52 53

    private lateinit var mDb:pedidoDataBase

54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
    companion object{
        private  const val LOCATION_PERMISSION_REQUEST_CODE=1
    }


    val PERMISSIONS_REQUEST_READ_CONTACTS = 100

    private val PROJECTION = arrayOf(
        ContactsContract.CommonDataKinds.Phone.CONTACT_ID,
        ContactsContract.Contacts.DISPLAY_NAME,
        ContactsContract.CommonDataKinds.Phone.NUMBER
    )

    private val markerClickListener = object: GoogleMap.OnMarkerClickListener{
        override fun onMarkerClick(marker: Marker?):Boolean{
            if(marker == selectedMarker){
                selectedMarker=null
                return true
            }
            selectedMarker =marker
            return false
        }
    }
Yannine Alvarez committed
77

78 79 80 81 82 83 84 85 86 87

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_maps)

        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        val mapFragment = supportFragmentManager
                .findFragmentById(R.id.map) as SupportMapFragment
        mapFragment.getMapAsync(this)

Yannine Alvarez committed
88 89 90 91

        // Initialize the room database
        mDb = pedidoDataBase.getInstance(applicationContext)

92 93 94 95 96 97 98
        fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)

        //intent para mandar a la siguiente pantalla el boton
        val myLayout: View = findViewById(R.id.menu_layout) // root View id from that link

        val myView: View = myLayout.findViewById(R.id.info_button)
        val ayudenme_button: View = myLayout.findViewById(R.id.help_button)
99 100
        val pendientes_button: View = myLayout.findViewById(R.id.fav_button)

101 102 103 104 105 106 107


        myView.setOnClickListener {
            Toast.makeText(this@MapsActivity, "Boton de info probar", Toast.LENGTH_SHORT).show()
            val i = Intent(this, InfoActivity::class.java)
      startActivity(i)

108
        }
109

110 111 112 113
        pendientes_button.setOnClickListener {
            Toast.makeText(this@MapsActivity, "Boton de info pendientes", Toast.LENGTH_SHORT).show()
            val i = Intent(this, PendienteLista::class.java)
            startActivity(i)
114 115 116 117 118 119 120 121 122 123 124
        }

        ayudenme_button.setOnClickListener {
            Toast.makeText(this@MapsActivity, "Boton de info probar ayudenme", Toast.LENGTH_SHORT).show()
            val url = "https://ayudapy.org/recibir"
            val i = Intent(Intent.ACTION_VIEW)
            i.data = Uri.parse(url)
            startActivity(i)

        }

125 126


127 128 129 130 131 132 133 134 135 136 137 138 139 140 141
        //agregar permiso para llamar
        val permissionCheck: Int = ContextCompat.checkSelfPermission(
            this, Manifest.permission.CALL_PHONE
        )
        if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
            Log.i("Mensaje", "No se tiene permiso para realizar llamadas telefónicas.")
            ActivityCompat.requestPermissions(
                this,
                arrayOf(Manifest.permission.CALL_PHONE),
                225
            )
        } else {
            Log.i("Mensaje", "Se tiene permiso!")
        }

Yannine Alvarez committed
142

143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352
    }


    /**
     * Manipulates the map once available.
     * This callback is triggered when the map is ready to be used.
     * This is where we can add markers or lines, add listeners or move the camera. In this case,
     * we just add a marker near Sydney, Australia.
     * If Google Play services is not installed on the device, the user will be prompted to install
     * it inside the SupportMapFragment. This method will only be triggered once the user has
     * installed Google Play services and returned to the app.
     */
    override fun onMapReady(googleMap: GoogleMap) {
        mMap = googleMap

        // Add a marker in Sydney and move the camera
       /* val sydney = LatLng(-34.0, 151.0)
        mMap.addMarker(MarkerOptions().position(sydney).title("Marker in Sydney"))
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(sydney, 15f))*/

        mMap.setOnMarkerClickListener(this)
        mMap.uiSettings.isZoomControlsEnabled = true

        setup()


        ApiService.redditClient.getListaCentro(15, 0).enqueue(
            object: Callback<CentroAyuda> {
                override fun onFailure(call: Call<CentroAyuda>, t: Throwable) {
                    t.printStackTrace()
                }

                override fun onResponse(call: Call<CentroAyuda>, response: Response<CentroAyuda>) {
                    if (response.isSuccessful) {
                        val listaCentro = response.body()
                        val CentroDeAyudas = listaCentro!!.results


                        var item = Int
                        for( item in CentroDeAyudas.indices ){
                            var name=listaCentro.results[item].name
                            var lat =listaCentro.results[item].location.coordinates
                            println("Este es el nombre $name")
                            println("Este son coordenadas $lat")
                            mMap.addMarker(
                                MarkerOptions()
                                    .position(LatLng(lat[1],lat[0]))
                                    .title(name)
                                    .icon(BitmapDescriptorFactory.fromResource(R.drawable.centro_donacion))
                            )
                        }

                        //print("Este es el centro ${CentroDeAyudas.size}")
                        //Log.d("centro","$CentroDeAyudas")


                    }else{

                        Toast.makeText(this@MapsActivity, "NO HUBO RESPUESTA EXITOSA", Toast.LENGTH_SHORT).show()
                    }
                }
            }
        )

        ApiService.stackClient.getListaPedidos(15, 0).enqueue(
            object: Callback<PedidosAyuda> {
                override fun onFailure(call: Call<PedidosAyuda>, t: Throwable) {
                    t.printStackTrace()
                }

                @RequiresApi(Build.VERSION_CODES.O)
                override fun onResponse(call: Call<PedidosAyuda>, response: Response<PedidosAyuda>) {
                    if (response.isSuccessful) {
                        val listaPedidos = response.body()
                        val PedidosDeAyudas = listaPedidos!!.features

                        var fec_actual = LocalDateTime.now()
                        var fec_actual_formato = DateTimeFormatter.ofPattern("yyyy-MM-dd")
                        var fec_actual_formateado = fec_actual.format(fec_actual_formato)
                        //print("La fecha es: $fec_actual_formateado")
                        for( item in PedidosDeAyudas.indices ){

                                var name=listaPedidos.features[item].properties.name
                                var id=listaPedidos.features[item].properties.pk.toInt()
                                var lat =listaPedidos.features[item].geometry.coordinates
                                //println("Este es el nombre $name")
                                //println("Este son coordenadas $lat")
                            // val bounds = LatLngBounds.Builder()//Prueba Bounds
                            mMap.addMarker(
                                MarkerOptions()
                                    .position(LatLng(lat[1],lat[0]))
                                    .title(name)
                                    .snippet(id.toString())
                                    .icon(BitmapDescriptorFactory.fromResource(R.drawable.pedido)
                                    )
                            )

                            //bounds.include(LatLng(lat[1],lat[0]))
                          //  moveCamera(CameraUpdateFactory.newLatLngBounds(bounds.build(), 50))
                           // println("Este es el id sin hacer clic $id")
                            mMap.setOnMarkerClickListener {marker ->
                                var marcador = marker.snippet
                             //   var filtrarMarcador = marcador.replace("m","")
                               // var idMarcador = filtrarMarcador.toInt()
                                //println("Este es el marcador filtrado ${marcador.replace("m","")}")
                                //println("Este es el id Marcador $idMarcador")
                                Toast.makeText(this@MapsActivity, "Este es el marker $marcador", Toast.LENGTH_SHORT).show()
                                callApiDetalle(marcador.toInt())
                                true
                            }
            
                        }//termina el for

                    }else{

                        Toast.makeText(this@MapsActivity, "NO HUBO RESPUESTA EXITOSA", Toast.LENGTH_SHORT).show()
                    }
                }
            }
        )


    }


    //llamar con la función a la siguiente api para los detalles de acuerdo al parametro ingresado, es decir de acuerdo a la url pk
    fun callApiDetalle(id: Int){
        ApiService.pedidoDetalle.getPedidoDetalle(id).enqueue(
         object: Callback<Resultado> {
             override fun onFailure(call: Call<Resultado>, t: Throwable) {
                 t.printStackTrace()
             }

             @RequiresApi(Build.VERSION_CODES.O)
             override fun onResponse(call: Call<Resultado>, response: Response<Resultado>) {
                 if (response.isSuccessful) {
                     val pedidoDetalle = response.body()

                     println("Probar pedido de Detalle $pedidoDetalle")

                     //fecha_publicado = findViewById(R.id.fecha_publicado)
                     // Publicado el 12 de abril de 2020 a las 00:04

                     val dialog = BottomSheetDialog(this@MapsActivity)
                     val view = layoutInflater.inflate(R.layout.fragment_pedido,null)
                     dialog.setContentView(view)
                     if (pedidoDetalle != null) {
                         view.fecha_publicado.setText("Publicado el ${pedidoDetalle.added}")
                         view.direccion_id.setText(pedidoDetalle.address)
                         view.contacto_id.setText(pedidoDetalle.name)
                         view.contacto_numero.setText(pedidoDetalle.phone)
                         view.pedido_id.setText(pedidoDetalle.title)
                         view.mensaje_id.setText(pedidoDetalle.message)
                     }
                     dialog.show()
                     view.llegar_id.setOnClickListener{
                         Toast.makeText(this@MapsActivity, "Boton de como llegar", Toast.LENGTH_SHORT).show()
                     }
                     view.contacto_numero.setOnClickListener{
                         val dialogo = layoutInflater.inflate(R.layout.alert_dialog_contacto,null)
                         val mBuilder =AlertDialog.Builder(this@MapsActivity)
                             .setView(dialogo)
                             .setTitle("¿Desea llamar o enviar mensaje?")
                         val mAlertDialog = mBuilder.show()

                         dialogo.llamar_contacto.setOnClickListener{
                             Toast.makeText(this@MapsActivity, "boton alerta llamar contacto", Toast.LENGTH_SHORT).show()
                             val i = Intent(Intent.ACTION_CALL)
                             i.data = Uri.parse("tel:${pedidoDetalle?.phone}")
                             if (ActivityCompat.checkSelfPermission(
                                     this@MapsActivity,
                                     Manifest.permission.CALL_PHONE
                                 ) != PackageManager.PERMISSION_GRANTED
                             ) {
                                 // TODO: Consider calling
                                 //    ActivityCompat#requestPermissions
                                 // here to request the missing permissions, and then overriding
                                 //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                                 //                                          int[] grantResults)
                                 // to handle the case where the user grants the permission. See the documentation
                                 // for ActivityCompat#requestPermissions for more details.
                                 return@setOnClickListener
                             }
                             startActivity(i)
                            // mAlertDialog.dismiss()
                         }

                         dialogo.msm_whatsapp.setOnClickListener {
                             Toast.makeText(this@MapsActivity, "boton alerta enviar mensaje whatsapp", Toast.LENGTH_SHORT).show()
                             //marcar que no existe el numero en mis contactos
                             val msj = "Mi mensaje es abcdef 1234567890"
                             val numeroTel = pedidoDetalle?.phone
                             val intent = Intent(Intent.ACTION_VIEW)
                             val uri =
                                 "whatsapp://send?phone=$numeroTel&text=$msj"
                             intent.data = Uri.parse(uri)
                             startActivity(intent)
                         }

                             Toast.makeText(this@MapsActivity, "Numero de contacto ${pedidoDetalle?.phone}", Toast.LENGTH_SHORT).show()

                     }
                    //Guardar los datos de la lista pendiente, usando la librería Room
                     view.pendiente_button.setOnClickListener{
                         Toast.makeText(this@MapsActivity, "Boton de pendiente ", Toast.LENGTH_SHORT).show()
                         //InsertTask(this, chapterObj).execute()
                        /* insertToDb(PedidoSave(pedidoDetalle!!.id,
                                                pedidoDetalle.title,pedidoDetalle.message,pedidoDetalle.name,pedidoDetalle.phone,
                         pedidoDetalle.address,pedidoDetalle.added))*/

Yannine Alvarez committed
353
                         // Initialize a new student
354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371
                         val pedido = Thread{
                             var pedidoEntity = PedidoSave()
                             pedidoEntity.id = pedidoDetalle!!.id
                             pedidoEntity.added = pedidoDetalle!!.added
                             pedidoEntity.address = pedidoDetalle!!.address
                             pedidoEntity.message = pedidoDetalle!!.message
                             pedidoEntity.name = pedidoDetalle!!.name
                             pedidoEntity.phone = pedidoDetalle!!.phone
                             pedidoEntity.title = pedidoDetalle!!.title

                             mDb.daoPedido().insert(pedidoEntity)

                             mDb.daoPedido().getAll().forEach()
                             {
                                 Log.i("Fetch Records", "Id: ${it.id}")

                                 println("Name es de pedido: ${it.name}")
                             }
Yannine Alvarez committed
372

373 374
                         }
                         pedido.start()
Yannine Alvarez committed
375

376
                        // imageView.setImageResource(R.drawable.icon_pendientes_checked)
Yannine Alvarez committed
377 378 379

                         view.pendiente_button.setBackgroundResource(R.drawable.icon_pendientes_checked)

380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439
                     }

                     view.listo_button.setOnClickListener{
                         Toast.makeText(this@MapsActivity, "boton de listo", Toast.LENGTH_SHORT).show()
                     }


                     Toast.makeText(this@MapsActivity, "Probar clic nuevo ${id}", Toast.LENGTH_SHORT).show()


                 }else{

                     Toast.makeText(this@MapsActivity, "El id es : $id", Toast.LENGTH_SHORT).show()
                 }
             }
         }
     )
    }


    //permiso para acceder a la ubicacion del dispositvo
    private fun setup(){
       if(ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED){
            ActivityCompat.requestPermissions(this,
            arrayOf(android.Manifest.permission.ACCESS_FINE_LOCATION),LOCATION_PERMISSION_REQUEST_CODE)
            return
        }

        mMap.isMyLocationEnabled= true

        fusedLocationClient.lastLocation.addOnSuccessListener(this){ location ->

            if(location != null){



                lastLocation = location
                val currentLatLong = LatLng(location.latitude, location.longitude)
                mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(currentLatLong, 18f))
            }

        }
    }

    override fun onMarkerClick(p0: Marker?): Boolean = false

    /*
    * CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngBounds(builder.build(), padding);
try {
    map.moveCamera(cameraUpdate);
} catch (Exception e) {
    int width = getResources().getDisplayMetrics().widthPixels;
    int height = getResources().getDisplayMetrics().heightPixels;
    cameraUpdate = CameraUpdateFactory.newLatLngBounds(builder.build(), width, height, padding);
    map.moveCamera(cameraUpdate);
}*/



}