package com.sunny.app.soft.timberkeyboardnew.ui.activity

import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.recyclerview.widget.LinearLayoutManager
import com.bumptech.glide.Glide
import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.load.engine.GlideException
import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.target.Target
import com.sunny.app.soft.timberkeyboardnew.App
import com.sunny.app.soft.timberkeyboardnew.R
import com.sunny.app.soft.timberkeyboardnew.data.entity.BackgroundEntity
import com.sunny.app.soft.timberkeyboardnew.databinding.ActivityDownloadBinding
import com.sunny.app.soft.timberkeyboardnew.room.MyDatabase
import com.sunny.app.soft.timberkeyboardnew.tools.AppConstant
import com.sunny.app.soft.timberkeyboardnew.tools.DialogStep
import com.sunny.app.soft.timberkeyboardnew.tools.KeyboardManager
import com.sunny.app.soft.timberkeyboardnew.tools.ZipTools
import com.sunny.app.soft.timberkeyboardnew.topon.AdManager
import com.sunny.app.soft.timberkeyboardnew.ui.adapter.KeyAdapter
import com.sunny.app.soft.timberkeyboardnew.ui.listener.ApplyListener
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.io.ByteArrayOutputStream
import java.io.File
import java.io.FileOutputStream
import java.io.InputStream

class DownloadActivity :
    BaseActivity(),
    View.OnClickListener,
    ApplyListener {

    private lateinit var binding: ActivityDownloadBinding

    private lateinit var backgroundEntity: BackgroundEntity


    private lateinit var unzipPath: String

    private lateinit var sp: SharedPreferences

    private var stepDialog: DialogStep? = null

    private var selectedStyle = 1

    private var appliedSkinNumber: String = ""

    private var appliedSkinStyle: Int = -1

    private var defaultStyle = 0
    override fun loadAd(): Boolean = true
    override fun setRootView(): View {
        binding = ActivityDownloadBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initView() {
        super.initView()
        binding.downloadProgress.visibility = View.VISIBLE
        backgroundEntity = intent.getSerializableExtra(AppConstant.KEY_EXTRA) as BackgroundEntity
        sp = getSharedPreferences(AppConstant.SHARE_NAME, Context.MODE_PRIVATE)
//        sp.registerOnSharedPreferenceChangeListener { sharedPreferences, key ->
//
//        }

        initImg()
        // unzipPath = /data/user/0/com.sunny.tools.app.soft.test/cache/skin_9
        unzipPath = ZipTools.getUnzipPath(backgroundEntity.skinNumber.toString())
        Log.d(App.TAG, "-------unzipPath=${unzipPath}")
        initDownload()
        initButton()
        initTitle()
    }

    private fun initTitle() {
        binding.bgName.text = "Keyboard background"
    }

    private fun initDownload() {
        val zipFile = File(unzipPath)
        if (!zipFile.exists()) {
            getZipData(
                backgroundEntity.contentPath,
                this@DownloadActivity,
                this
            )
        } else {
            binding.downloadProgress.visibility = View.GONE
            initStyleList()
        }
    }

    private fun initStyleList() {
        val listOf = mutableListOf<String>()
        backgroundEntity.skinNumber.let {
            for (i in 0 until 5) {
                val plus = unzipPath + "/" + AppConstant.getnormalBg(it.toString(), i + 1)
                Log.d(App.TAG, "-------plus=${plus}")
                if (File(plus).exists()) {
                    listOf.add(plus)
                }
            }
        }
        Log.d(App.TAG, "-------initList=${listOf.size}")
        val keyAdapter = KeyAdapter(this, defaultStyle, listOf) {
            selectedStyle = it + 1
            if (appliedSkinNumber == backgroundEntity.skinNumber.toString()) {
                updateBtn(appliedSkinStyle == selectedStyle)
            }
        }
        binding.listRecycler.run {
            adapter = keyAdapter
            layoutManager = LinearLayoutManager(this@DownloadActivity).apply {
                orientation = LinearLayoutManager.HORIZONTAL
            }
        }
    }

    private fun onShowAd() {
        AdManager.showTopOn(this) {
            startSetSkin()

        }


    }

    private fun initButton() {
        binding.downloadBack.setOnClickListener(this)
        binding.btnDownload.setOnClickListener(this)
        binding.imLike.setOnClickListener(this)
    }

    /**
     * isApplied 是否已经apply
     */
    private fun updateBtn(isApplied: Boolean) {
        binding.btnDownload.isSelected = isApplied
        binding.btnDownload.isEnabled = !isApplied
        if (isApplied) {
            binding.btnDownload.text = getString(R.string.applied)
        } else {
            binding.btnDownload.text = getString(R.string.apply)
        }

    }

    private fun initImg() {
        appliedSkinNumber = sp.getString(AppConstant.KEY_CUR_Skin_Number, "") ?: run { "-1" }
        appliedSkinStyle = sp.getInt(AppConstant.KEY_CUR_STYLE, -1)
        if (appliedSkinNumber == backgroundEntity.skinNumber.toString()) {
            updateBtn(appliedSkinStyle == selectedStyle)
        }else{
            updateBtn(false)
        }
        binding.imLike.isSelected = backgroundEntity.like
        try {
            Glide
                .with(this)
                .asDrawable()
                .load(backgroundEntity.coverPath)
                .thumbnail(0.1f)
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .skipMemoryCache(true)
                .into(binding.downloadImg)

        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    override fun onClick(v: View?) {
        when (v) {
            binding.downloadBack -> finish()
            binding.btnDownload -> {
                applySkin()
            }

            binding.imLike -> {
                binding.imLike.isSelected = !binding.imLike.isSelected
            }
        }
    }

    override fun onPause() {
        super.onPause()
        CoroutineScope(Dispatchers.IO).launch {
            MyDatabase.myDatabase.BackgroundEntityDao().updateCollect(backgroundEntity.apply {
                like = binding.imLike.isSelected
            })

        }
    }

    private fun applySkin() {
        if (!KeyboardManager.isChoose() || !KeyboardManager.isEnable()) {
            if (stepDialog == null) {
                stepDialog = DialogStep.newInstance(this@DownloadActivity) {
                    if (KeyboardManager.isChoose() && KeyboardManager.isEnable()) {
                        onShowAd()
                    }
                }
            }
            stepDialog?.show(supportFragmentManager, "")
            return
        }
        onShowAd()
    }

    private fun startSetSkin() {
        binding.downloadProgress.visibility = View.VISIBLE
        val zipFile = File(unzipPath)
        if (zipFile.exists()) {
            apply()
        }
    }

    private fun apply() {
        val edit = sp.edit()
        edit.run {
            putString(AppConstant.KEY_CUR_Skin_Number, backgroundEntity.skinNumber.toString())
            putInt(AppConstant.KEY_CUR_STYLE, selectedStyle)
            putString(AppConstant.KEY_CUR_Bg, backgroundEntity.coverPath)
            apply()
            Log.d(App.TAG, "------putConfig ----skin_Number =  ${ backgroundEntity.skinNumber} style=${selectedStyle} ")
        }

        binding.downloadProgress.visibility = View.GONE
        Toast.makeText(this, getString(R.string.succ_apply), Toast.LENGTH_LONG).show()
        startActivity(Intent(this@DownloadActivity, DisplayActivity::class.java))
        finish()

    }

    private fun getZipData(
        contentPath: String,
        context: Context,
        listener: ApplyListener
    ) {
        Glide.with(context).asFile().load(contentPath).addListener(object : RequestListener<File> {
            override fun onLoadFailed(
                e: GlideException?,
                model: Any?,
                target: Target<File>,
                isFirstResource: Boolean
            ): Boolean {
                listener.applyListener(false, "")
                return false
            }

            override fun onResourceReady(
                resource: File,
                model: Any,
                target: Target<File>?,
                dataSource: DataSource,
                isFirstResource: Boolean
            ): Boolean {
                Log.d(App.TAG, "-------zipFilepath=${resource.absolutePath}")
                saveFile(resource.absolutePath, listener)
                return false
            }

        }).preload()
    }

    private fun saveFile(
        zipFilepath: String,
        listener: ApplyListener
    ) {
        ZipTools.unzip(zipFilepath, unzipPath, listener)

    }

    private fun writeNewFile(input: InputStream, filePath: String): Boolean {
        var stream: FileOutputStream? = null
        var outStream: ByteArrayOutputStream? = null
        try {
            val outStream = ByteArrayOutputStream()
            val bytes = ByteArray(4096)
            var length = 0
            while (input.read(bytes).also {
                    length = it
                } != -1) {
                outStream.write(bytes, 0, length)
            }
            val file = File(filePath)
            if (!file.exists()) {
                file.createNewFile()
            }
            stream = FileOutputStream(file)
            stream.run {
                write(outStream.toByteArray())
            }
            outStream.close()
            stream.close()
            return true
        } catch (ex: Exception) {
            outStream?.close()
            stream?.close()
            return false
        }
    }

    override fun applyListener(isSuccess: Boolean, str: String) {
        unzipPath = str
        binding.downloadProgress.visibility = View.GONE
        if (isSuccess) {
            Log.d(App.TAG, "----解压-true")
            initStyleList()
        } else {
            Toast.makeText(this, getString(R.string.reenter), Toast.LENGTH_LONG).show()
        }
    }

}