package com.assimilate.alltrans.viewui

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.speech.tts.TextToSpeech
import android.view.View
import androidx.activity.OnBackPressedCallback
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.recyclerview.widget.LinearLayoutManager
import com.assimilate.alltrans.MyApp
import com.assimilate.alltrans.R
import com.assimilate.alltrans.adapters.TranslationAdapter
import com.assimilate.alltrans.adapters.TranslationAdapter.TranslationItemCallback
import com.assimilate.alltrans.common.FirebaseAnalyticsHelper
import com.assimilate.alltrans.common.LolAdWrapper
import com.assimilate.alltrans.common.Widget
import com.assimilate.alltrans.databinding.ActivityHistoryBinding
import com.assimilate.alltrans.mydb.DbTranslation
import com.assimilate.alltrans.mydb.Translations
import com.lol.apex.ok.google.adlibrary.base.listener.LolLoadError
import com.lol.apex.ok.google.adlibrary.base.listener.LolShowError
import java.util.Locale

class HistoryActivity : AppCompatActivity() {
    private var tts: TextToSpeech? = null
    private var binding: ActivityHistoryBinding? = null
    private var ids: HashSet<Long>? = null // 通过id 删除数据库文件
    private var items: HashSet<Int>? = null // 通许index 删除界面上面的数据
    private var operationCollection = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        binding = ActivityHistoryBinding.inflate(layoutInflater)
        setContentView(binding!!.root)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v: View, insets: WindowInsetsCompat ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(26, systemBars.top, 26, systemBars.bottom)
            insets
        }

        ids = HashSet()
        items = HashSet()


        val extra = intent.getStringExtra(COMMAND)
        operationCollection = COMMAND_COLLECTION == extra

        tts = TextToSpeech(this) { status ->
            if (null != tts && TextToSpeech.SUCCESS == status) tts!!.setLanguage(
                Locale.getDefault()
            )
        }

        initClick()

    }

    override fun onResume() {
        super.onResume()
        initSet()
    }

    private fun initSet() {
        val translations = ArrayList<Translations>()
        if (!operationCollection) {
            // 查出收藏的翻译记录
            binding!!.tvFuncTrans.text = getString(R.string.favor_title)
            val list = DbTranslation(this).getTranslations(true)
            if (list.isEmpty()) {
                binding!!.llEmptyFav.visibility = View.VISIBLE
                binding!!.remove.visibility = View.GONE
            } else {
                binding!!.llEmptyFav.visibility = View.GONE
                binding!!.remove.visibility = View.GONE
            }
            if (null != list && list.isNotEmpty()) {
                translations.addAll(list)
            }
        } else {
            // 查出所有的翻译记录
            binding!!.tvFuncTrans.text = getString(R.string.his_title)
            val list = DbTranslation(this).getTranslations(false)
            if (list.isEmpty()) {
                binding!!.remove.visibility = View.GONE
                binding!!.llEmptyHis.visibility = View.VISIBLE
            } else {
                binding!!.remove.visibility = View.GONE
                binding!!.llEmptyHis.visibility = View.GONE
            }
            if (null != list && list.isNotEmpty()) {
                translations.addAll(list)
            }
        }
        val adapter = TranslationAdapter(translations, object : TranslationItemCallback {
            override fun updateList(
                operation: TranslationAdapter.Operation,
                id: Long,
                position: Int
            ) {
                if (TranslationAdapter.Operation.ADD == operation) {
                    add(id, position)
                } else if (TranslationAdapter.Operation.REMOVE == operation) {
                    remove(id, position)
                }
                updateBtn()
            }

            override fun speech(value: String) {
                if (null != tts
                    && TextToSpeech.LANG_NOT_SUPPORTED != tts!!.isLanguageAvailable(Locale.getDefault())
                ) {
                    tts!!.speak(value, 0, null, null)
                }
            }

            private fun add(id: Long, index: Int) {
                ids!!.add(id)

                items!!.add(index)
            }

            private fun remove(id: Long, index: Int) {
                ids!!.remove(id)
                items!!.remove(index)
                FirebaseAnalyticsHelper.historyDeleteEvent()
            }

            private fun updateBtn() {
                if (ids!!.isEmpty()) {
                    binding!!.remove.visibility = View.GONE
                } else {
                    binding!!.remove.visibility = View.VISIBLE
                }
            }
        })
        val layoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)

        binding!!.remove.setOnClickListener(object : View.OnClickListener {
            private var dbTranslation: DbTranslation? = null

            override fun onClick(v: View) {
                if (ids!!.isEmpty()) {
                    Widget.makeToast(this@HistoryActivity, "Nothing to remove.")
                    return
                }

                if (ids!!.isNotEmpty()) {
                    val longArrayList = ArrayList(ids)
                    if (!operationCollection) {
                        getDbTranslation(this@HistoryActivity).removeCollectTranslations(
                            longArrayList
                        )
                    } else {
                        getDbTranslation(this@HistoryActivity).removeTranslations(longArrayList)
                    }
                    ids!!.clear()
                }
                if (items!!.isNotEmpty()) {
                    val integerArrayList = ArrayList(items)
                    integerArrayList.sortWith { o1, o2 -> o2.compareTo(o1) }
                    adapter.updateSet(integerArrayList)
                    items!!.clear()
                }
                binding!!.remove.visibility = View.GONE // 隐藏删除按钮
            }

            private fun getDbTranslation(context: Context): DbTranslation {
                if (null == dbTranslation) {
                    dbTranslation = DbTranslation(context)
                }
                return dbTranslation!!
            }
        })

        binding!!.histories.layoutManager = layoutManager
        binding!!.histories.adapter = adapter

        adLoad(MyApp.Config.history_int_auto)
        backPressedCall()

    }

    private fun initClick() {
        binding?.ivHisBack?.setOnClickListener {
            showInstAdFromCache(MyApp.Config.history_int_auto)
            finish()
        }
        binding?.emtpoyHisNow?.setOnClickListener {
            finish()
        }
        binding?.emtpoyFavNow?.setOnClickListener {
            startActivity(Intent(this, MainActivity::class.java))
        }
    }

    private fun backPressedCall() {
        val callback = object : OnBackPressedCallback(true) {
            override fun handleOnBackPressed() {
                showInstAdFromCache(MyApp.Config.history_int_auto)
                finish()
            }
        }
        onBackPressedDispatcher.addCallback(this, callback)
    }


    private fun adLoad(place: String) {
        // 加载广告
        LolAdWrapper.shared.loadAdIfNotCached(
            this,
            place,
            object : LolAdWrapper.LoLLoadListener {
                override fun loadFailed(error: LolLoadError?) {

                }

                override fun loaded() {
                    // 处理加载成功
                }
            })

    }

    private fun showInstAdFromCache(place: String) {
        // 如果需要立刻展示广告，可以调用展示方法
        LolAdWrapper.shared.showAdIfCached(
            this,
            place,
            object : LolAdWrapper.LolShowListener {
                override fun shown() {
                    // 处理广告展示成功
                }

                override fun showFailed(error: LolShowError?) {
                    // 处理广告展示失败
                    finish()
                }

                override fun closed() {
                    // 处理广告关闭
                    finish()
                }
            })
    }

    companion object {
        const val COMMAND: String = "remove"
        const val COMMAND_COLLECTION: String = "remove_collection"
    }
}