package com.keyboard.craft.activity

import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import com.keyboard.craft.CraftApp
import com.keyboard.craft.R
import com.keyboard.craft.ad.MaxManager
import com.keyboard.craft.bean.DetailsBean
import com.keyboard.craft.bean.ItemDataBean
import com.keyboard.craft.databinding.UiDetailsActivityBinding
import com.keyboard.craft.util.AppSharedPreferences
import com.keyboard.craft.util.NetworkCallback
import com.keyboard.craft.util.NetworkUtil
import com.keyboard.craft.util.OnDownloadListener
import com.keyboard.craft.util.ResourceDownloadUtil
import com.keyboard.craft.util.UIHelper
import com.keyboard.craft.util.fileIsDownload
import com.keyboard.craft.util.loadRoundedImage
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class DetailsActivity : AppCompatActivity(), OnDownloadListener {
    companion object {
        const val KEY_CRAFT_DETAILS_BEAN = "key_details_bean"
        const val KEY_CRAFT_FROM = "key_from"
    }

    private lateinit var binding: UiDetailsActivityBinding
    private var bean: ItemDataBean? = null
    private var detailsBean: DetailsBean? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = UiDetailsActivityBinding.inflate(layoutInflater)
        setContentView(binding.root)
        bean = intent.getSerializableExtra(KEY_CRAFT_DETAILS_BEAN) as ItemDataBean?
        val from = intent.getStringExtra(KEY_CRAFT_FROM)
        MaxManager.onLoadAd()
        MaxManager.startShowMaxAd(this) {}

        initBar()
        initView()
        initData()

    }

    private fun initBar() {
        UIHelper.setupStatusBar(this, true, binding.view)
    }

    private fun initView() {
        GlobalScope.launch {
            val current = CraftApp.databaseManager.getItemDataBeanFileByPath(bean?.key!!)
            withContext(Dispatchers.Main) {
                if (current?.isLiked == true) {
                    binding.likeImg.setImageResource(R.drawable.like_select_icon)
                } else {
                    binding.likeImg.setImageResource(R.drawable.like_unselect_icon)
                }
                bean?.isLiked = current?.isLiked == true
            }

        }

        binding.likeBtn.setOnClickListener {

            MaxManager.startShowMaxAd(this) {
                bean?.isLiked = bean?.isLiked != true
                if (bean?.isLiked == true) {
                    binding.likeImg.setImageResource(R.drawable.like_select_icon)
                } else {
                    binding.likeImg.setImageResource(R.drawable.like_unselect_icon)
                }
                GlobalScope.launch {
                    if (bean?.isLiked == true) {
                        CraftApp.databaseManager.insertItemDataBeanFile(bean!!)
                    } else {
                        CraftApp.databaseManager.deleteItemDataBeanFile(bean!!)
                    }
                }

            }

        }

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

        binding.downBtn.setOnClickListener {

            MaxManager.startShowMaxAd(this@DetailsActivity) {
                detailsBean?.let {
                    updateDownloadBtn(it)
                    val resourceHandler = ResourceDownloadUtil(this@DetailsActivity) // 传入当前上下文
                    resourceHandler.setOnDownloadListener(this@DetailsActivity)
                    val imageUrl = it.themeContent.androidRawZipUrl
                    val b = fileIsDownload(this@DetailsActivity, imageUrl)
                    if (b) {
                        AppSharedPreferences(this@DetailsActivity).setCurrentlyThemeUrl(imageUrl)
                        val intent = Intent(this@DetailsActivity, 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
    }

    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!!)
        val imageUrl = detailsBean?.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()
        }
    }
}