package com.base.scanqrclear.ui.contact

import android.Manifest
import android.content.Intent
import android.net.Uri
import androidx.activity.addCallback
import androidx.core.view.updatePadding
import androidx.core.widget.addTextChangedListener
import androidx.lifecycle.lifecycleScope
import com.base.scanqrclear.R
import com.base.scanqrclear.ads.AdsMgr
import com.base.scanqrclear.ads.AdsShowCallBack
import com.base.scanqrclear.base.BaseActivity
import com.base.scanqrclear.bean.ContractUIBean
import com.base.scanqrclear.bean.config.AdConfigBean
import com.base.scanqrclear.databinding.ActivityContractBinding
import com.base.scanqrclear.utils.BarUtils
import com.base.scanqrclear.utils.ContactUtils.queryMediaContract
import com.base.scanqrclear.utils.IntentUtils.intentPickContacts
import com.base.scanqrclear.utils.LogEx
import com.base.scanqrclear.utils.PermissionUtils.checkContactsReadPermission
import com.base.scanqrclear.utils.ToastUtils.toast
import com.google.gson.Gson
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

class ContractActivity : BaseActivity<ActivityContractBinding>(ActivityContractBinding::inflate) {

    private val contractUIBean = ContractUIBean()

    override fun onResumeOneShoot() {
        super.onResumeOneShoot()
        val flag = changeLanguage()
        if (flag) return
    }

    override fun initView() {
        super.initView()
        binding.clTop.updatePadding(top = BarUtils.getStatusBarHeight())
        AdsMgr.showNative(binding.flAd, R.layout.layout_admob_item)
    }

    override fun initListener() {
        super.initListener()
        onBackPressedDispatcher.addCallback {
            if (AdConfigBean.adsConfigBean.functionBackShowAd) {
                AdsMgr.showInsert(this@ContractActivity, false, object : AdsShowCallBack() {
                    override fun close(where: Int) {
                        finishToMainTop()
                    }

                    override fun failed(where: Int) {
                        finishToMainTop()
                    }

                    override fun googleFailed(where: Int) {
                        finishToMainTop()
                    }
                })
            } else {
                finishToMainTop()
            }
        }
        binding.flBack.setOnClickListener {
            onBackPressedDispatcher.onBackPressed()
        }
        binding.editFullName.addTextChangedListener { s ->
            contractUIBean.n = s.toString()
        }
        binding.editAddress.addTextChangedListener { s ->
            contractUIBean.adr = s.toString()
        }
        binding.editPhone.addTextChangedListener { s ->
            contractUIBean.tel = s.toString()
        }
        binding.editEmail.addTextChangedListener { s ->
            contractUIBean.email = s.toString()
        }
        binding.tvSelect.setOnClickListener {
            if (!checkContactsReadPermission()) {
                launcher.launch(arrayOf(Manifest.permission.READ_CONTACTS)) {
                    if (checkContactsReadPermission()) {
                        pickContract()
                    }
                }
            } else {
                pickContract()
            }
        }
        binding.flQueren.setOnClickListener {
            if (contractUIBean.n.isEmpty()) {
                toast("Enter invalidate full name contact", true)
                return@setOnClickListener
            }
            if (contractUIBean.adr.isEmpty()) {
                toast("Enter invalidate address", true)
                return@setOnClickListener
            }
            if (contractUIBean.tel.isEmpty()) {
                toast("Enter invalidate telephone number", true)
                return@setOnClickListener
            }
            if (contractUIBean.email.isEmpty()) {
                toast("Enter invalidate email", true)
                return@setOnClickListener
            }
            if (AdConfigBean.adsConfigBean.functionUseShowAd) {
                AdsMgr.showInsert(this, true, object : AdsShowCallBack() {
                    override fun close(where: Int) {
                        jumpCodeActivity()
                    }

                    override fun failed(where: Int) {
                        jumpCodeActivity()
                    }

                    override fun googleFailed(where: Int) {
                        jumpCodeActivity()
                    }
                })
            } else {
                jumpCodeActivity()
            }

        }
    }

    private fun jumpCodeActivity() {
        startActivity(Intent(this, ContractCodeActivity::class.java).apply {
            putExtra("data", Gson().toJson(contractUIBean))
        })
        finish()
    }

    private fun pickContract() {
        val intent = intentPickContacts()
        launcher.launch(intent) { result ->
            val contactUri: Uri? = result.data?.data
            LogEx.logDebug(TAG, "contactUri=$contactUri")
            if (contactUri != null) {
                lifecycleScope.launch(Dispatchers.IO) {
                    val media = queryMediaContract(contactUri)
                    LogEx.logDebug(TAG, "media=$media")
                    if (media != null) {
                        contractUIBean.n = media.name
                        if (media.phoneList.isNotEmpty()) {
                            contractUIBean.tel = media.phoneList.first()
                        }
                        if (media.emailList.isNotEmpty()) {
                            contractUIBean.email = media.emailList.first()
                        }
                        if (media.addressList.isNotEmpty()) {
                            contractUIBean.adr = media.addressList.first()
                        }
                    }
                    launch(Dispatchers.Main) {
                        binding.editFullName.setText(contractUIBean.n)
                        binding.editAddress.setText(contractUIBean.adr)
                        binding.editPhone.setText(contractUIBean.tel)
                        binding.editEmail.setText(contractUIBean.email)
                    }
                }
            }

        }
    }


}