package com.base.scanqr.ui.product

import android.content.ActivityNotFoundException
import android.content.Intent
import android.net.Uri
import android.os.Environment
import android.widget.Toast
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.ProductUIBean
import com.base.scanqr.databinding.ActivityProductCodeBinding
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.LogEx
import com.base.scanqr.utils.QRCodeUtils.generateEAN13Barcode
import com.base.scanqr.utils.SpJsonUtils
import com.base.scanqr.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 tempImage: String = ""

    override fun onResumeOneShoot() {
        super.onResumeOneShoot()
        val flag = changeLanguage()
        if (flag) return
    }
    override fun initView() {
        super.initView()
        binding.clTop.updatePadding(top = BarUtils.getStatusBarHeight())

        val data = intent.extras?.getString("data")
        data?.let {
            productUIBean = Gson().fromJson(data, ProductUIBean::class.java)
            binding.tvContent.text = productUIBean.content
        }

        Thread {
            val bitmap = generateEAN13Barcode(productUIBean.content, 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) {
                        tempImage = file.absolutePath
                    }
                }
                if (productUIBean.needCreate) {
                    productUIBean.needCreate = false
                    SpJsonUtils.addJsonBean<ProductUIBean>(FunctionUIBean.KEY_PRODUCT, productUIBean)
                }
            }
        }.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.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, productUIBean.content)
            toast("Copied to clipboard", true)
        }
        binding.flSearch.setOnClickListener {

            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()
            }
        }
    }

}