package com.example.myapplication

import android.app.Activity
import android.app.AlertDialog
import android.content.Context
import android.content.Intent
import android.net.Uri
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.provider.ContactsContract
import android.util.Log
import androidx.core.app.ActivityCompat.startActivityForResult
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import kotlinx.android.synthetic.main.fragment_slideshow.*

class contacto : MainActivity() {

    val REQUEST_PHONE_NUMBER = 1
    lateinit var contactUri: Uri

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


        select_phone_number.setOnClickListener {

            val intent = Intent(Intent.ACTION_PICK)
            intent.type = ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE

            if (intent.resolveActivity(packageManager) != null) {
                startActivityForResult(intent, REQUEST_PHONE_NUMBER)
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        if(requestCode == REQUEST_PHONE_NUMBER && resultCode == Activity.RESULT_OK) {
            contactUri = data!!.data as Uri

            getPhoneNumber()
        }
    }

    data class Contact(val name:String, val phone:String)

    private fun getPhoneNumber(){


        val sharedPreferences = getSharedPreferences("CONTACTS", Context.MODE_PRIVATE)
        val editor = sharedPreferences.edit()
        val projection = arrayOf(ContactsContract.CommonDataKinds.Phone.NUMBER,ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)
        val cursor = contentResolver.query(contactUri , projection, null,null)

        if(cursor!!.moveToFirst()){

            val name = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME))
            val phoneNumber = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER))
            val contactstring = sharedPreferences.getString("contact", "0")

            if(contactstring == "0" ) {

                var hashMap: HashMap<String, String> = HashMap<String, String>()
                hashMap.put(name, phoneNumber)
                val gson = Gson()
                val hashMapString: String = gson.toJson(hashMap)

                editor.putString("contact", hashMapString)
                editor.commit()
            }

            else {

                val gson = Gson()
                val type = object : TypeToken<HashMap<String,String>>() {}.type
                val jsonMap : HashMap <String,String> = gson.fromJson(contactstring, type)
                jsonMap.put(name, phoneNumber)

                if (jsonMap.size <= 10) {

                    val json = gson.toJson(jsonMap)

                    Log.d("json", json)
                    Log.d("json", jsonMap.size.toString())

                    editor.putString("contact", json)
                    editor.commit()
                }

                else{

                    val builder = AlertDialog.Builder(this)
                    builder.setTitle("Maximo numero de contactos")
                    builder.setMessage("Llegaste al maximo de contactos de emergencias, borre los contactos para agregar mas")
                    // Finally, make the alert dialog using builder
                    val dialog: AlertDialog = builder.create()
                    // Display the alert dialog on app interface
                    dialog.show()
                }
            }

            val gson2 = Gson()
            val contactstring2 = sharedPreferences.getString("contact", "0")
            val json2 = gson2.toJson(contactstring2)
            display_phone_number.text = "\n $name phone number:\n $phoneNumber"


            Log.d("json", json2)

        }
    }

}
