package com.app.keyboard.colorful.activity

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.drawable.Drawable
import android.os.Bundle
import android.util.Log
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.isVisible
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.app.keyboard.colorful.MyApp
import com.app.keyboard.colorful.R
import com.app.keyboard.colorful.ada.AdaOther
import com.app.keyboard.colorful.dbbase.DbHelper
import com.app.keyboard.colorful.colorlistener.cOnApplyListener
import com.app.keyboard.colorful.colorlistener.COnClickListener
import com.app.keyboard.colorful.data.ChildBean
import com.app.keyboard.colorful.helper.CommonUtils
import com.app.keyboard.colorful.helper.Sp
import com.bumptech.glide.Glide
import com.bumptech.glide.integration.webp.decoder.WebpDrawable
import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.engine.GlideException
import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.target.Target
import kotlinx.coroutines.launch
import java.io.File


class ActivityDownload : AppCompatActivity() {
    companion object {
        @JvmField
        val SOURCE_KEY = "data_key"
    }


    private lateinit var displayUrl: String
    private lateinit var gifUrl: String
    private lateinit var zipUrl: String
    private lateinit var name: String
    private lateinit var applyBtn: LinearLayout
    private lateinit var imgData: ImageView
    private lateinit var imgBack: ImageView
    private lateinit var textName: TextView

    private lateinit var recommendedRecycler: RecyclerView


    private lateinit var loadingLayout: FrameLayout

    private lateinit var unzipPath: String

    private lateinit var tvDownload: TextView
    private lateinit var imDownload: ImageView

    private lateinit var thumb: String

    private lateinit var imgLike: ImageView

    private lateinit var data: ChildBean

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_download)
        CommonUtils.initFullScreen(this,true)

        findViewId()
        getExtraData()
        displayData()
        setApply()
        onClick()
    }


    private fun getExtraData() {
        data = intent.getSerializableExtra(SOURCE_KEY) as ChildBean
        displayUrl = data.imgPath
        zipUrl = data.zipPath
        name = data.titleName
        gifUrl = data.imgGif
        data.thumbGif?.let {
            thumb = it
        }
        data.thumbUrl?.let {
            thumb = it
        }


        val serviceZipName = com.app.keyboard.colorful.helper.ZipUtils.getServiceZipName(zipUrl)
        Log.d(MyApp.TAG, "--------serviceZipName=$serviceZipName")
        unzipPath = com.app.keyboard.colorful.helper.ZipUtils.getUnzipPath(serviceZipName)


        lifecycleScope.launch {
            DbHelper.getIsLike(name) {
                imgLike.isSelected = it
            }
        }

        if (File(unzipPath).exists()) {
            imDownload.isVisible = false
            tvDownload.text = getString(R.string.color_apply)
        } else {
            imDownload.isVisible = true
            tvDownload.text = getString(R.string.color_download_apply)
        }

    }

    private fun findViewId() {
        applyBtn = findViewById(R.id.layoutDownloadApply)
        imgData = findViewById(R.id.image_data)
        imgBack = findViewById(R.id.back)
        textName = findViewById(R.id.textview_data_name)
        recommendedRecycler = findViewById(R.id.recommended_recycler)

        imgLike = findViewById(R.id.im_like)
        loadingLayout = findViewById(R.id.loading)
        imDownload = findViewById(R.id.im_download)
        tvDownload = findViewById(R.id.tv_download)
    }

    private fun displayData() {
        textName.text = name
        if (gifUrl.isNotEmpty()) {
            loadImgGif()
        } else {
            Glide.with(this)
                .load(displayUrl)
                .placeholder(R.drawable.def_placeholder)
                .thumbnail(Glide.with(this).load(thumb))
                .into(imgData)
        }
    }


    private fun onClick() {
        imgBack.setOnClickListener {
            finish()
        }

        imgLike.setOnClickListener {
            imgLike.isSelected = !imgLike.isSelected

            lifecycleScope.launch {
                if (imgLike.isSelected) {
                    DbHelper.addLike(data)
                } else {
                    DbHelper.removeLike(data)
                }
            }
        }
        val forYouList = MyApp.list.filter {
            it.parentName == getString(R.string.color_recommend_name)

        }

        recommendedRecycler.run {
            adapter =  AdaOther(
                this@ActivityDownload
            ).apply {
                val shuffled = forYouList[0].keyboardList.shuffled()
                setForYouList(shuffled.subList(0,8))
            }.apply {
                setClickAction(object : COnClickListener {
                    override fun onItemClick() {
                        finish()
                    }

                })
            }

            layoutManager = GridLayoutManager(this@ActivityDownload, 2)

        }

    }

    @SuppressLint("CheckResult")
    private fun loadImgGif() {
        Glide.with(this)
            .load(gifUrl)
            .placeholder(R.drawable.def_placeholder)
            .thumbnail(Glide.with(this).load(thumb))
            .addListener(object : RequestListener<Drawable> {
                override fun onLoadFailed(
                    e: GlideException?,
                    model: Any?,
                    target: Target<Drawable>,
                    isFirstResource: Boolean
                ): Boolean {

                    return false
                }

                override fun onResourceReady(
                    resource: Drawable,
                    model: Any,
                    target: Target<Drawable>?,
                    dataSource: DataSource,
                    isFirstResource: Boolean
                ): Boolean {
                    if (resource is WebpDrawable) {
                        resource.loopCount = WebpDrawable.LOOP_FOREVER
                    }

                    return false
                }

            }).into(imgData)
    }

    private fun setApply() {
        applyBtn.setOnClickListener {
            startDown()

        }
    }



    private fun startDown() {
        loadingLayout.isVisible = true
        applyBtn.isEnabled = false

        val file = File(unzipPath)
        if (file.exists()) {
            val findFirstDirectory = com.app.keyboard.colorful.helper.ZipUtils.findFirstDirectory(file)

            apply("${findFirstDirectory}/")
            applyBtn.isEnabled = true
            loadingLayout.isVisible = false
        } else {
            com.app.keyboard.colorful.helper.ZipUtils.startDownloadZip(zipUrl, object :
                cOnApplyListener {
                override fun OnApplySkinListener(fileList: List<File?>?) {
                    runOnUiThread {
                        applyBtn.isEnabled = true
                        loadingLayout.isVisible = false
                    }
                    if (fileList.isNullOrEmpty()) {
                        runOnUiThread {
                            Toast.makeText(
                                this@ActivityDownload,
                                getString(R.string.color_download_fail),
                                Toast.LENGTH_SHORT
                            ).show()
                        }
                    } else {
//                        lifecycleScope.launch {
//                            DbHelper.addDownload(data)
//                        }
                        if (file.exists()) {
                            val findFirstDirectory = com.app.keyboard.colorful.helper.ZipUtils.findFirstDirectory(file)
                            Log.d(
                                MyApp.TAG,
                                "----apply------------it=$findFirstDirectory"
                            )
                            runOnUiThread {
                                apply("${findFirstDirectory}/")

                            }
                        }
                    }


                }

            })
        }

    }

    private fun apply(path: String) {
        var skinParentPath = path
        if (path.contains("res")) {
            skinParentPath = path.substringBeforeLast("res")
        }


        Sp.updateSkinPath(skinParentPath)
        Toast.makeText(
            this@ActivityDownload,
            getString(R.string.color_theme_application_successful),
            Toast.LENGTH_SHORT
        ).show()
        startActivity(Intent(this, ActivityPreView::class.java).apply {
            putExtra(ActivityPreView.key_name, name)
        })
        finish()
    }




}