package com.base.scanqr.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.scanqr.R
import com.base.scanqr.ads.AdsMgr
import com.base.scanqr.ads.AdsShowCallBack
import com.base.scanqr.base.BaseActivity
import com.base.scanqr.bean.MessageUIBean
import com.base.scanqr.databinding.ActivityMessageBinding
import com.base.scanqr.utils.BarUtils
import com.base.scanqr.utils.ContactUtils.queryTel
import com.base.scanqr.utils.IntentUtils.intentPickContacts
import com.base.scanqr.utils.LogEx
import com.base.scanqr.utils.PermissionUtils.checkContactsReadPermission
import com.base.scanqr.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 {
            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()
                }
            })
        }
        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
            }
            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)
        }
    }
}