package com.colorful.keyboard.theme

import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import com.colorful.keyboard.theme.ad.AdsInsUtil
import com.colorful.keyboard.theme.bean.DetailsBean
import com.colorful.keyboard.theme.bean.DownloadBean
import com.colorful.keyboard.theme.databinding.ColorfulDetailsActivityBinding
import com.colorful.keyboard.theme.myutil.AppSharedPreferences
import com.colorful.keyboard.theme.myutil.NetworkCallback
import com.colorful.keyboard.theme.myutil.NetworkUtil
import com.colorful.keyboard.theme.myutil.OnDownloadListener
import com.colorful.keyboard.theme.myutil.ResourceDownloadUtil
import com.colorful.keyboard.theme.myutil.fileIsDownload
import com.colorful.keyboard.theme.myutil.loadRoundedImage
import com.gyf.immersionbar.ktx.immersionBar
import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch

@OptIn(DelicateCoroutinesApi::class)
class ColorfulDetailsActivity : AppCompatActivity(), OnDownloadListener {
    private var key: String? = null
    private var title: String? = null
    private lateinit var binding: ColorfulDetailsActivityBinding
    private var detailsBean: DetailsBean? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ColorfulDetailsActivityBinding.inflate(layoutInflater)
        setContentView(binding.root)
        title = intent.getStringExtra("title")
        key = intent.getStringExtra("key")
        if (key.isNullOrEmpty()) {
            finish()
        }
        initBar()
        initView()
        initData()
        AdsInsUtil.loadAllAdIsNotCached(this)
    }

    private fun initBar() {
        immersionBar {
            statusBarDarkFont(true)
            statusBarView(binding.view)
        }
    }

    override fun onBackPressed() {
        super.onBackPressed()
        AdsInsUtil.showAdRandomModeAndTiming(this)
    }

    private fun initView() {
        binding.titleTv.text = title
        binding.backBtn.setOnClickListener { onBackPressed() }

        binding.downBtn.setOnClickListener {
            detailsBean?.let {
                updateDownloadBtn(it)
                val resourceHandler = ResourceDownloadUtil(this) // 传入当前上下文
                resourceHandler.setOnDownloadListener(this)
                val imageUrl = it.themeContent.androidRawZipUrl
                val b = fileIsDownload(this, imageUrl)
                if (b) {
                    AppSharedPreferences(this).setCurrentlyThemeUrl(imageUrl)

                    val intent = Intent(this, PreviewActivity::class.java)
                    intent.putExtra(PreviewActivity.KEY_PREVIEW_URL, imageUrl)
                    startActivity(intent)
                    finish()
                } else {
                    binding.loadingBar.visibility = View.VISIBLE
                    binding.downIcon.visibility = View.GONE
                    resourceHandler.downloadAndExtractResources(imageUrl)//文件不存在则下载
                }
            }
        }
    }

    private fun initData() {
        loadingPlay()
        NetworkUtil().getResourceRequest(key!!, object : NetworkCallback<DetailsBean> {
            override fun onSuccess(data: DetailsBean) {
                detailsBean = data
                updateUi(data)
            }

            override fun onFailure(errorMessage: String) {
                runOnUiThread {
                    if (!isFinishing && !isDestroyed) {
                        loadingClose()
                    }
                }
            }
        })
    }

    private fun updateUi(data: DetailsBean) {
        runOnUiThread {
            if (!isFinishing && !isDestroyed) {
                loadingClose()

                updateDownloadBtn(data)

                var url = data.themeContent.imgGif
                if (url.isEmpty()) {
                    url = data.themeContent.img
                }
                loadRoundedImage(this, url, binding.imageView, 40)
            }
        }
    }

    private fun loadingPlay() {
        binding.loadingLayout.visibility = View.VISIBLE
    }

    private fun loadingClose() {
        binding.loadingLayout.visibility = View.GONE
    }

    private fun updateDownloadBtn(data: DetailsBean) {
        if (fileIsDownload(this, data.themeContent.androidRawZipUrl)) {
            if (AppSharedPreferences(this).getCurrentlyThemeUrl() == data.themeContent.androidRawZipUrl) {
                binding.downTv.text = getString(R.string.applied)
                binding.downBtn.isClickable = false
                binding.downBtn.isFocusable = false
                binding.downIcon.visibility = View.GONE
            } else {
                binding.downTv.text = getString(R.string.apply_it)
                binding.downBtn.isClickable = true
                binding.downBtn.isFocusable = true
                binding.downIcon.visibility = View.GONE
            }
        } else {
            binding.downTv.text = getString(R.string.download)
            binding.downBtn.isClickable = true
            binding.downBtn.isFocusable = true
            binding.downIcon.visibility = View.VISIBLE
        }
    }

    override fun onDownloadComplete(isDownloaded: Boolean) {

        binding.loadingBar.visibility = View.GONE
        binding.downIcon.visibility = View.GONE

        updateUi(detailsBean!!)

        GlobalScope.launch(Dispatchers.IO) {
            var url = detailsBean?.themeContent?.imgGif
            if (url.isNullOrEmpty()) {
                url = detailsBean?.themeContent?.img
            }
            val bean = DownloadBean(
                title = detailsBean?.title ?: "", key = detailsBean?.key ?: "", imgUrl = url ?: ""
            )
            App.downloadManager.insertDownloadBean(bean)
        }
    }
}