package com.base.scanqr.ui.contact

import android.Manifest
import android.os.Environment
import androidx.activity.addCallback
import androidx.core.view.updatePadding
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.ContractUIBean
import com.base.scanqr.bean.FunctionUIBean
import com.base.scanqr.databinding.ActivityContractCodeBinding
import com.base.scanqr.ui.widget.InputNameDialog.showInputNameDialog
import com.base.scanqr.utils.BarUtils
import com.base.scanqr.utils.BitmapUtils.saveBitmapToFile
import com.base.scanqr.utils.ClipboardUtils.copyText
import com.base.scanqr.utils.IntentUtils.intentShareImage
import com.base.scanqr.utils.IntentUtils.intentWriteContract
import com.base.scanqr.utils.LogEx
import com.base.scanqr.utils.QRCodeUtils.generateQRCode
import com.base.scanqr.utils.SpJsonUtils
import com.base.scanqr.utils.ToastUtils.toast
import com.google.gson.Gson
import java.io.File

class ContractCodeActivity : BaseActivity<ActivityContractCodeBinding>(ActivityContractCodeBinding::inflate) {


    private var contractUIBean = ContractUIBean()
    private var tempImage: String = ""
    private var contractQrString = ""

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

        AdsMgr.showBanner(binding.flBanner, false)
    }

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


        val data = intent.extras?.getString("data")
        data?.let {
            contractUIBean = Gson().fromJson(data, ContractUIBean::class.java)
            binding.tvName.text = contractUIBean.n
            binding.tvTel.text = contractUIBean.tel
            binding.tvEmail.text = contractUIBean.email
            binding.tvAddress.text = contractUIBean.adr
        }
        Thread {
            contractQrString = ContractUIBean.createContractQrString(contractUIBean)
            LogEx.logDebug(TAG, "contractQrString=$contractQrString")
            val bitmap = generateQRCode(contractQrString, 735, 735, 5)
            runOnUiThread {
                binding.ivQr.setImageBitmap(bitmap)
                val file = File(cacheDir, System.currentTimeMillis().toString() + ".jpg")
                bitmap?.let {
                    val flag = saveBitmapToFile(it, file.absolutePath)
                    LogEx.logDebug(TAG, "flag=$flag tempImage=${file.absolutePath}")
                    if (flag) {
                        tempImage = file.absolutePath
                    }
                }
                if (contractUIBean.needCreate) {
                    contractUIBean.needCreate = false
                    SpJsonUtils.addJsonBean<ContractUIBean>(FunctionUIBean.KEY_CONTACT, contractUIBean)
                }
            }
        }.start()
    }

    override fun initListener() {
        super.initListener()
        onBackPressedDispatcher.addCallback {
            AdsMgr.showInsert(this@ContractCodeActivity, 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.llShare.setOnClickListener {
            val intent = intentShareImage(this, tempImage)
            runCatching {
                startActivity(intent)
            }
        }
        binding.llPdf.setOnClickListener {
            toast("没实现")
        }
        binding.llDownload.setOnClickListener {
            kotlin.runCatching {
                val appFile = File(
                    Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),
                    this.resources.getString(R.string.app_name)
                )
                if (!appFile.exists()) appFile.mkdirs()
                var newName = File(tempImage).name
                showInputNameDialog(newName) { name ->
                    if (name.endsWith(".jpg")) {
                        name.also { newName = it }
                    } else {
                        newName = "$name.jpg"
                    }
                    val downFile = File(appFile, newName)
                    downFile.createNewFile()
                    File(tempImage).copyTo(downFile, true)
                    toast("Save to:${appFile.absolutePath}", true)
                }
            }
        }
        binding.llCopy.setOnClickListener {
            copyText(TAG, contractQrString)
            toast("Copied to clipboard", true)
        }
        binding.flSearch.setOnClickListener {
            try {
                val intent = intentWriteContract(contractUIBean)
                startActivity(intent)
            } catch (e: Exception) {
                toast("No application was found to handle the add contract", true)

            }

        }
    }

}