package com.example.ayudapy import android.Manifest import android.content.Entity 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 androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProviders import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView 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 kotlinx.android.synthetic.main.info.* import kotlinx.android.synthetic.main.pendientes_lista.* import org.jetbrains.anko.doAsync 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 private lateinit var mDb:pedidoDataBase 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 } } 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) // Initialize the room database mDb = pedidoDataBase.getInstance(applicationContext) 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) val pendientes_button: View = myLayout.findViewById(R.id.fav_button) myView.setOnClickListener { Toast.makeText(this@MapsActivity, "Boton de info probar", Toast.LENGTH_SHORT).show() val i = Intent(this, InfoActivity::class.java) startActivity(i) } pendientes_button.setOnClickListener { Toast.makeText(this@MapsActivity, "Boton de info pendientes", Toast.LENGTH_SHORT).show() val i = Intent(this, PendienteLista::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!") } } /** * 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 { override fun onFailure(call: Call, t: Throwable) { t.printStackTrace() } override fun onResponse(call: Call, response: Response) { 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 { override fun onFailure(call: Call, t: Throwable) { t.printStackTrace() } @RequiresApi(Build.VERSION_CODES.O) override fun onResponse(call: Call, response: Response) { 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 { override fun onFailure(call: Call, t: Throwable) { t.printStackTrace() } @RequiresApi(Build.VERSION_CODES.O) override fun onResponse(call: Call, response: Response) { 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))*/ // Initialize a new student 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}") }*/ } pedido.start() // imageView.setImageResource(R.drawable.icon_pendientes_checked) view.pendiente_button.setBackgroundResource(R.drawable.icon_pendientes_checked) } 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); }*/ }