package com.base.scanqrclear.ui.message

import android.annotation.SuppressLint
import android.content.Intent
import android.net.Uri
import android.view.MotionEvent
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.MessageUIBean
import com.base.scanqrclear.bean.config.AdConfigBean
import com.base.scanqrclear.databinding.ActivityMessageBinding
import com.base.scanqrclear.utils.BarUtils
import com.base.scanqrclear.utils.ContactUtils.queryTel
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 MessageActivity : BaseActivity<ActivityMessageBinding>(ActivityMessageBinding::inflate) {

    private var messageUIBean = MessageUIBean()

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

    @SuppressLint("ClickableViewAccessibility")
    override fun initListener() {
        super.initListener()
        onBackPressedDispatcher.addCallback {
            if (AdConfigBean.adsConfigBean.functionBackShowAd) {
                AdsMgr.showInsert(this@MessageActivity, 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.editPhone.addTextChangedListener { s ->
            messageUIBean.smsto = s.toString()
        }
        binding.editContent.addTextChangedListener { s ->
            messageUIBean.msg = s.toString()
        }
        binding.editPhone.setOnTouchListener { v, event ->
            if (event.action == MotionEvent.ACTION_UP) {
                val x = event.x.toInt()
                val y = event.y.toInt()
                val drawableEnd = binding.editPhone.compoundDrawablesRelative[2]
                if (drawableEnd != null) {
                    val drawableWidth = drawableEnd.intrinsicWidth
                    val drawableHeight = drawableEnd.intrinsicHeight

                    val paddingEnd = binding.editPhone.paddingEnd

                    val left = binding.editPhone.width - drawableWidth - paddingEnd
                    val right = binding.editPhone.width - paddingEnd
                    val top = (binding.editPhone.height - drawableHeight) / 2
                    val bottom = top + drawableHeight
                    if (x in left..right && y in top..bottom) {
                        onDrawableClicked()
                        return@setOnTouchListener true
                    }
                }
            }
            return@setOnTouchListener false
        }
        binding.flQueren.setOnClickListener {
            if (messageUIBean.smsto.isEmpty()) {
                toast("Enter phone number", true)
                return@setOnClickListener
            }
            if (messageUIBean.msg.isEmpty()) {
                toast("Enter your message here...", 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, MessageCodeActivity::class.java).apply {
            putExtra("data", Gson().toJson(messageUIBean))
        })
        finish()
    }

    private fun onDrawableClicked() {
        LogEx.logDebug(TAG, "onDrawableClicked")
        if (!checkContactsReadPermission()) {
            launcher.launch(arrayOf(android.Manifest.permission.READ_CONTACTS)) {
                if (checkContactsReadPermission()) {
                    pickTel()
                }
            }
        } else {
            pickTel()
        }
    }

    private fun pickTel() {
        val intent = intentPickContacts()
        try {
            launcher.launch(intent) { result ->
                val contactUri: Uri? = result.data?.data
                LogEx.logDebug(TAG, "")
                if (contactUri != null) {
                    lifecycleScope.launch(Dispatchers.IO) {
                        val tel = queryTel(contactUri) ?: ""
                        messageUIBean.smsto = tel
                        launch(Dispatchers.Main) {
                            binding.editPhone.setText(tel)
                        }
                    }
                }

            }
        } catch (e: Exception) {
            toast("No application was found to handle the contacts pick", true)
        }
    }
}