package com.base.scanqrclear.ui.product

import android.content.ActivityNotFoundException
import android.content.Intent
import android.net.Uri
import android.widget.Toast
import androidx.activity.addCallback
import androidx.core.view.updatePadding
import androidx.lifecycle.ViewModelProvider
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.FunctionUIBean
import com.base.scanqrclear.bean.ProductUIBean
import com.base.scanqrclear.bean.config.AdConfigBean
import com.base.scanqrclear.databinding.ActivityProductCodeBinding
import com.base.scanqrclear.ui.vm.QrViewModel
import com.base.scanqrclear.ui.widget.InputNameDialog.showInputNameDialog
import com.base.scanqrclear.utils.BarUtils
import com.base.scanqrclear.utils.BitmapUtils.saveBitmapToFile
import com.base.scanqrclear.utils.ClipboardUtils.copyText
import com.base.scanqrclear.utils.IntentUtils.intentShareImage
import com.base.scanqrclear.utils.LogEx
import com.base.scanqrclear.utils.QRCodeUtils.generateEAN13Barcode
import com.base.scanqrclear.utils.SpJsonUtils
import com.base.scanqrclear.utils.ToastUtils.toast
import com.google.gson.Gson
import java.io.File

/**
 * https://juejin.cn/post/6844904163755687944
 * EAN-13 格式
 */
class ProductCodeActivity : BaseActivity<ActivityProductCodeBinding>(ActivityProductCodeBinding::inflate) {

    private var productUIBean = ProductUIBean()
    private var qrString: String = ""
    private var tempImagePath: String = ""

    private val viewModel by lazy(LazyThreadSafetyMode.NONE) {
        ViewModelProvider(this)[QrViewModel::class.java]
    }

    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 {
            productUIBean = Gson().fromJson(data, ProductUIBean::class.java)
            qrString = productUIBean.content
            binding.tvContent.text = productUIBean.content
        }

        Thread {
            val bitmap = generateEAN13Barcode(qrString, 648, 255)
            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) {
                        tempImagePath = file.absolutePath
                    }
                }
                if (productUIBean.needCreate) {
                    productUIBean.needCreate = false
                    SpJsonUtils.addJsonBean<ProductUIBean>(FunctionUIBean.KEY_PRODUCT, productUIBean)
                }
            }
        }.start()

    }

    override fun initListener() {
        super.initListener()
        onBackPressedDispatcher.addCallback {
            if (AdConfigBean.adsConfigBean.functionBackShowAd) {
                AdsMgr.showInsert(this@ProductCodeActivity, 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.llShare.setOnClickListener {
            val intent = intentShareImage(this, qrString)
            runCatching {
                startActivity(intent)
            }
        }
        binding.llDownload.setOnClickListener {
            if (AdConfigBean.adsConfigBean.functionUseShowAd) {
                AdsMgr.showInsert(this, true, object : AdsShowCallBack() {
                    override fun close(where: Int) {
                        useDownload()
                    }

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

                    override fun googleFailed(where: Int) {
                        useDownload()
                    }
                })
            } else {
                useDownload()
            }
        }
        binding.llCopy.setOnClickListener {
            copyText(TAG, productUIBean.content)
            toast("Copied to clipboard", true)
        }
        binding.flSearch.setOnClickListener {
            if (AdConfigBean.adsConfigBean.functionUseShowAd) {
                AdsMgr.showInsert(this, true, object : AdsShowCallBack() {
                    override fun close(where: Int) {
                        useSearch()
                    }

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

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

        }
    }

    fun useDownload() {
        kotlin.runCatching {
            val newName = File(qrString).name
            showInputNameDialog(newName) { name ->
                viewModel.copyFileToDownloads(this, name, tempImagePath)
            }
        }
    }

    fun useSearch(){
        val intent = Intent(Intent.ACTION_VIEW)
        intent.setData(Uri.parse("https://www.google.com/search?q=${productUIBean.content}"))

        try {
            startActivity(intent)
        } catch (e: ActivityNotFoundException) {
            toast("")
            Toast.makeText(this, "No application was found to handle the search request", Toast.LENGTH_SHORT).show()
        }
    }

}