package com.base.scanqrclear.ui.wifi

import android.content.Intent
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.FunctionUIBean.Companion.KEY_PRODUCT
import com.base.scanqrclear.bean.FunctionUIBean.Companion.KEY_WIFI
import com.base.scanqrclear.bean.WifiUIBean
import com.base.scanqrclear.bean.WifiUIBean.Companion.createWifiQRString
import com.base.scanqrclear.bean.config.AdConfigBean
import com.base.scanqrclear.databinding.ActivityWifiCodeBinding
import com.base.scanqrclear.ui.exportpdf.ExportPdfActivity
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.IntentUtils.intentWifiSettings
import com.base.scanqrclear.utils.LogEx
import com.base.scanqrclear.utils.QRCodeUtils.generateQRCode
import com.base.scanqrclear.utils.SpJsonUtils
import com.base.scanqrclear.utils.ToastUtils.toast
import com.google.gson.Gson
import com.gyf.immersionbar.ktx.immersionBar
import java.io.File

class WifiCodeActivity : BaseActivity<ActivityWifiCodeBinding>(ActivityWifiCodeBinding::inflate) {

    private var wifiBean: WifiUIBean = WifiUIBean()
    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")
        LogEx.logDebug(TAG, "data=$data")
        data?.let {
            wifiBean = Gson().fromJson(data, WifiUIBean::class.java)
            if (wifiBean.securityId == 0) {
                binding.tvSecurity.text = "WPA/WPA2"
            }
            if (wifiBean.securityId == 1) {
                binding.tvSecurity.text = "WEP"
            }
            binding.tvSsid.text = wifiBean.ssid
            binding.tvPassword.text = wifiBean.password
            if (wifiBean.hidden) {
                binding.tvHidden.text = "YES"
            } else {
                binding.tvHidden.text = "NO"
            }

            qrString = createWifiQRString(wifiBean)
            LogEx.logDebug(TAG, "wifiContent=$qrString")
        }

        Thread {
            val bitmap = generateQRCode(qrString, 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) {
                        tempImagePath = file.absolutePath
                    }
                }
                if (wifiBean.needCreate) {
                    wifiBean.needCreate = false
                    SpJsonUtils.addJsonBean<WifiUIBean>(FunctionUIBean.KEY_WIFI, wifiBean)
                }
            }
        }.start()

    }

    override fun initListener() {
        super.initListener()
        onBackPressedDispatcher.addCallback {
            if (AdConfigBean.adsConfigBean.functionBackShowAd) {
                AdsMgr.showInsert(this@WifiCodeActivity, 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, tempImagePath)
            runCatching {
                startActivity(intent)
            }
        }
        binding.llPdf.setOnClickListener {
            startActivity(Intent(this, ExportPdfActivity::class.java).apply {
                putExtra("qrType", KEY_WIFI)
                putExtra("qrString", qrString)
            })
        }
        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, qrString)
            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()
            }
        }
    }

    override fun configSystemBar() {
        immersionBar {
            statusBarColor("#FFFFFFFF")
            statusBarDarkFont(true)
        }
    }

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

    fun useSearch() {
        val wifiIntent = intentWifiSettings()
        kotlin.runCatching {
            startActivity(wifiIntent)
        }
    }

}