package com.base.scanqr.ui.wifi

import android.os.Environment
import androidx.activity.addCallback
import androidx.core.view.updatePadding
import com.base.scanqr.R
import com.base.scanqr.base.BaseActivity
import com.base.scanqr.bean.FunctionUIBean
import com.base.scanqr.bean.WifiUIBean
import com.base.scanqr.databinding.ActivityWifiCodeBinding
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.intentWifiSettings
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 com.gyf.immersionbar.ktx.immersionBar
import java.io.File

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

    private var wifiBean: WifiUIBean = WifiUIBean()
    private var wifiContent: String = ""
    private var tempImage: String = ""
    override fun initView() {
        super.initView()
        binding.clTop.updatePadding(top = BarUtils.getStatusBarHeight())

        val data = intent.extras?.getString("data")
        LogEx.logDebug(TAG, "data=$data")
        data?.let {
            wifiBean = Gson().fromJson(data, WifiUIBean::class.java)
        }

        val content = StringBuilder()
        content.append("WIFI:")
        content.append("T:")
        if (wifiBean.securityId == 0) {
            content.append("WPA/WPA2").append(";")
            binding.tvSecurity.text = "WPA/WPA2"
        }
        if (wifiBean.securityId == 1) {
            content.append("WEP").append(";")
            binding.tvSecurity.text = "WEP"
        }
        if (wifiBean.securityId == 2) {
            content.append(";")
        }
        content.append("S:")
        content.append(wifiBean.ssid).append(";")
        content.append("P:")
        content.append(wifiBean.password).append(";")
        content.append("H:")
        content.append(wifiBean.hidden).append(";")

        wifiContent = content.toString()
        LogEx.logDebug(TAG, "wifiContent=$wifiContent")

        binding.tvSsid.text = wifiBean.ssid
        binding.tvPassword.text = wifiBean.password
        if (wifiBean.hidden) {
            binding.tvHidden.text = "YES"
        } else {
            binding.tvHidden.text = "NO"
        }
        Thread {
            val bitmap = generateQRCode(wifiContent, 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 (wifiBean.needCreate) {
                    wifiBean.needCreate = false
                    SpJsonUtils.addJsonBean<WifiUIBean>(FunctionUIBean.KEY_WIFI, wifiBean)
                }
            }
        }.start()

    }

    override fun initListener() {
        super.initListener()
        onBackPressedDispatcher.addCallback {
            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, wifiContent)
            toast("Copied to clipboard", true)
        }
        binding.flSearch.setOnClickListener {
            val wifiIntent = intentWifiSettings()
            kotlin.runCatching {
                startActivity(wifiIntent)
            }
        }
    }

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

}