package com.input.board.appskey.keyboard.viewUi

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.drawable.Drawable
import android.os.Bundle
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
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 com.input.board.appskey.keyboard.KeyBoardApp
import com.input.board.appskey.keyboard.R
import com.input.board.appskey.keyboard.fileTools.DownloadZip
import com.input.board.appskey.keyboard.fileTools.InputMethodCom
import com.input.board.appskey.keyboard.fileTools.SpSkin
import com.input.board.appskey.keyboard.interf.onApplyCallback
import com.input.board.appskey.keyboard.interf.onClickCallback
import com.input.board.appskey.keyboard.recyAdapter.ForYouAdapter
import java.io.File

class ApplyActivity : AppCompatActivity() {
    companion object {
        @JvmField
        var DISPLAY_URL_KEY: String = "display_url_key"

        @JvmField
        val ZIP_URL_KEY = "zip_url_key"


        @JvmField
        val NAME_KEY = "name_key"

        @JvmField
        val GIF_KEY = "gif_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 viewAllLayout: LinearLayout

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_apply)
        showInterAd{

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




    private fun getExtraData() {
        displayUrl = intent.getStringExtra(DISPLAY_URL_KEY).toString()
        zipUrl = intent.getStringExtra(ZIP_URL_KEY).toString()
        name = intent.getStringExtra(NAME_KEY).toString()
        gifUrl = intent.getStringExtra(GIF_KEY).toString()


    }

    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)
        viewAllLayout = findViewById(R.id.layout_view_all)
    }

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


    private fun onClick() {
        imgBack.setOnClickListener {
            finish()
        }
        viewAllLayout.setOnClickListener {
            startActivity(Intent(this, ViewAllActivity::class.java))
            finish()
        }

        val forYouList = KeyBoardApp.list.filter {
            it.parentName == "for you"

        }

        recommendedRecycler.run {
            adapter = ForYouAdapter(this@ApplyActivity).apply {
                val shuffled = forYouList[0].keyboardList.shuffled()
                setForYouList(shuffled)
            }.apply {
                setClickAction(object : onClickCallback {
                    override fun onClickCall() {
                        finish()
                    }

                })
            }

            layoutManager = GridLayoutManager(this@ApplyActivity, 2)

        }

    }

    @SuppressLint("CheckResult")
    private fun loadImgGif() {
        Glide.with(this).load(gifUrl).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 {
            val checkEnable = InputMethodCom.checkEnable(this)
            val checkSetDefault = InputMethodCom.checkSetDefault(this)
            if (!checkEnable || !checkSetDefault) {
                Toast.makeText(
                    this@ApplyActivity,
                    getString(R.string.text_promt),
                    Toast.LENGTH_SHORT
                ).show()
                startActivity(Intent(this, KeyBoardSettingActivity::class.java))
                return@setOnClickListener
            }
            startDown()

        }
    }

    private fun startDown() {
        applyBtn.isEnabled = false
        DownloadZip.startDownloadZip(zipUrl, object : onApplyCallback {
            override fun onApplyResult(fileList: List<File?>?) {
                runOnUiThread {
                    applyBtn.isEnabled = true
                }
                if (fileList.isNullOrEmpty()) {
                    runOnUiThread {
                        Toast.makeText(
                            this@ApplyActivity,
                            getString(R.string.download_fail),
                            Toast.LENGTH_SHORT
                        ).show()
                    }
                } else {
                    fileList[0]?.path?.let {
                        runOnUiThread {
                            showInterAd {
                                apply(it)
                            }
                        }

                    }
                }


            }

        })
    }

    private fun apply(path: String) {
        val skinParentPath = path.substringBeforeLast("res")
        SpSkin.updateSkinPath(skinParentPath)
        Toast.makeText(
            this@ApplyActivity,
            getString(R.string.theme_application_successful),
            Toast.LENGTH_SHORT
        ).show()
    }

    private fun showInterAd(action:()->Unit) {
        action.invoke()
    }
}