package com.base.scanqr.ui.event

import android.annotation.SuppressLint
import android.os.Environment
import androidx.activity.addCallback
import androidx.core.view.updatePadding
import androidx.lifecycle.ViewModelProvider
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.EventUIBean
import com.base.scanqr.bean.FunctionUIBean
import com.base.scanqr.databinding.ActivityEventCodeBinding
import com.base.scanqr.ui.vm.QrViewModel
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.intentAddCalendar
import com.base.scanqr.utils.IntentUtils.intentShareImage
import com.base.scanqr.utils.KotlinExt.toFormatTime5
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 EventCodeActivity : BaseActivity<ActivityEventCodeBinding>(ActivityEventCodeBinding::inflate) {

    private var eventUIBean = EventUIBean()
    private var tempImagePath: String = ""
    private var qrString = ""
    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)
    }

    @SuppressLint("SetTextI18n")
    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 {
            eventUIBean = Gson().fromJson(data, EventUIBean::class.java)
            binding.tvDateTime.text = eventUIBean.startTime.toFormatTime5() + " - " + eventUIBean.endTime.toFormatTime5()
            binding.tvLocation.text = eventUIBean.location
            binding.tvDesc.text = eventUIBean.description
        }
        Thread {
            qrString = EventUIBean.createEventQRString(eventUIBean)
            LogEx.logDebug(TAG, "eventQrString=$qrString")
            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 (eventUIBean.needCreate) {
                    eventUIBean.needCreate = false
                    SpJsonUtils.addJsonBean<EventUIBean>(FunctionUIBean.KEY_EVENT, eventUIBean)
                }
            }
        }.start()
    }


    override fun initListener() {
        super.initListener()
        onBackPressedDispatcher.addCallback {
            AdsMgr.showInsert(this@EventCodeActivity, 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, tempImagePath)
            runCatching {
                startActivity(intent)
            }
        }
        binding.llPdf.setOnClickListener {
            toast("没实现")
        }
        binding.llDownload.setOnClickListener {
            kotlin.runCatching {
                val newName = File(tempImagePath).name
                showInputNameDialog(newName) { name ->
                    viewModel.copyFileToDownloads(this, name, tempImagePath)
                }
            }
        }
        binding.llCopy.setOnClickListener {
            copyText(TAG, qrString)
            toast("Copied to clipboard", true)
        }
        binding.flSearch.setOnClickListener {
            val intent = intentAddCalendar(eventUIBean)
            try {
                startActivity(intent)
                finish()
            } catch (e: Exception) {
                toast("No application was found to handle the calendar event request", true)
            }
        }
    }

}