package com.keyboard.journey

import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import com.gyf.immersionbar.ktx.immersionBar
import com.keyboard.journey.bean.DetailsBean
import com.keyboard.journey.bean.ItemDataBean
import com.keyboard.journey.databinding.JourneyDetailsActivityBinding
import com.keyboard.journey.topon.AdManager
import com.keyboard.journey.util.AppSharedPreferences
import com.keyboard.journey.util.NetworkCallback
import com.keyboard.journey.util.NetworkUtil
import com.keyboard.journey.util.OnDownloadListener
import com.keyboard.journey.util.ResourceDownloadUtil
import com.keyboard.journey.util.fileIsDownload
import com.keyboard.journey.util.loadRoundedImage
import org.libpag.PAGFile

class JourneyDetailsActivity : AppCompatActivity(), OnDownloadListener {
    companion object {
        const val KEY_JOURNEY_DETAILS_BEAN = "key_journey_details_bean"
    }

    private lateinit var binding: JourneyDetailsActivityBinding
    private var bean: ItemDataBean? = null
    private val appSharedPreferences = lazy { AppSharedPreferences(this) }
    private var detailsBean: DetailsBean? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = JourneyDetailsActivityBinding.inflate(layoutInflater)
        setContentView(binding.root)
        bean = intent.getSerializableExtra(KEY_JOURNEY_DETAILS_BEAN) as ItemDataBean?
        initBar()
        initView()
        initData()

    }

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

    private fun initView() {
        binding.titleTv.text = bean?.title
        binding.backBtn.setOnClickListener { finish() }

        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) {
                    AdManager.showAD(this@JourneyDetailsActivity){type->
                        if (type == AdManager.type_show_close || type == AdManager.type_show_fail || type == AdManager.type_no_cache){
                            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(bean?.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
        val pagFile = PAGFile.Load(assets, "loading.pag")
        binding.pagView.composition = pagFile
        binding.pagView.setRepeatCount(0)
        binding.pagView.play()
    }

    private fun loadingClose() {
        binding.loadingLayout.visibility = View.GONE
        if (binding.pagView.isPlaying) {
            binding.pagView.stop()
        }
    }

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