MapsActivity.kt 17 KB
Newer Older
1 2 3 4 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 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 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 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396
package com.example.ayudapy

import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.database.Observable
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.*
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter

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

    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
        }
    }
    private var pedidoDatabase:PedidoDataBase? = null

    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)

        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)


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


        }

        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)

        }

        //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!")
        }

        pedidoDatabase = PedidoDataBase.getInstance(this)
    }


    /**
     * 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))*/

                     }

                     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()
                 }
             }
         }
     )
    }

   /* fun insertToDb(pedido:PedidoSave){

    }*/

    //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);
}*/



}