package pxds.czbe.twvj

import android.app.AppOpsManager
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import android.view.View
import com.test.basd.supercleanermax.R
import com.test.basd.supercleanermax.databinding.LshfbiBinding
import net.sourceforge.pinyin4j.PinyinHelper
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination
import pxds.dlpf.buoz.fico.Vzaf.showAppDetailDialog
import pxds.etmo.Jmyh
import pxds.hpls.xkxo.Dpse
import pxds.lmmd.zmwf.Egac
import pxds.lmmd.zmwf.Hoph
import pxds.lmmd.zmwf.Khko.setTrackedOnClickListener
import pxds.lmmd.zmwf.Khko.string
import pxds.lmmd.zmwf.Wecj
import pxds.vazp.Rorl

class Roik : Wecj<LshfbiBinding>() {

    private var list = arrayListOf<Rorl>()

    override val binding: LshfbiBinding by lazy {
        LshfbiBinding.inflate(layoutInflater)
    }

    var isAsc: Boolean = true

    private var adapter: Dpse? = null

    private lateinit var launcher: Hoph

    private var needPermission: Boolean = false

    private var type: Int = 0

    private var isRefreshData = false

    private val TAG = R.string.ރޞޜމޢ_D.string()

    override fun onResume() {
        super.onResume()
        if (checkUsageAccessSettings(requireContext())) {
            binding.dfrpswo.visibility = View.GONE
            binding.okpgtql.visibility = View.VISIBLE
        }
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

    }

    private fun orderList() {
        when (type) {
            APP_LIST_TYPE_NAME -> {
                list.forEach {
                    it.pinYin = getPinyin(it.appName)
                }
                if (isAsc) {
                    list.sortBy { it.pinYin }
                } else {
                    list.sortByDescending { it.pinYin }
                }
            }

            APP_LIST_TYPE_INSTALL -> {
                if (isAsc) {
                    list.sortBy { it.installTime }
                } else {
                    list.sortByDescending { it.installTime }
                }
            }

            APP_LIST_TYPE_SIZE -> {
                if (isAsc) {
                    list.sortBy { it.appSize }
                } else {
                    list.sortByDescending { it.appSize }
                }

            }

            APP_LIST_TYPE_LAST_USE -> {
                if (isAsc) {
                    list.sortBy { it.lastUsedTime }
                } else {
                    list.sortByDescending { it.lastUsedTime }
                }
            }
        }
    }

    companion object {
        const val APP_LIST_TYPE_NAME = 12
        const val APP_LIST_TYPE_INSTALL = 15
        const val APP_LIST_TYPE_SIZE = 19
        const val APP_LIST_TYPE_LAST_USE = 123
    }

    fun showContent(isRefresh: Boolean = false) {
        if (isRefresh) {
            binding.okpgtql.visibility = View.VISIBLE
        }
    }

    fun refreshFragmentData(dataList: List<Rorl>, isRefresh: Boolean = false, index: Int = 0) {
        isRefreshData = true
        Egac.logDebug(TAG, R.string.ވދދޚޣ_D.string((isRefresh).toString(), (isVisible).toString(), (index).toString()))
        if (isRefresh && isVisible) {
            binding.dfrpswo.visibility = View.GONE
            binding.dboqifh.visibility = View.GONE
            setDataRefresh(dataList)
        } else {
            setData(dataList)
        }

    }

    fun setData(dataList: List<Rorl>) {
        list.clear()
        list.addAll(dataList)
        orderList()
    }

    fun getPinyin(str: String): String {

        val format = HanyuPinyinOutputFormat()
        format.caseType = HanyuPinyinCaseType.UPPERCASE
        format.toneType = HanyuPinyinToneType.WITHOUT_TONE
        val sb = StringBuilder()

        val strNoSpace = str.replace(R.string.ދށސޖޝ_D.string().toRegex(), "").trim()

        val charArray = strNoSpace.toCharArray()
        for (i in charArray.indices) {
            val c = charArray[i]

            if (Character.isWhitespace(c)) {
                continue
            }

            if (c.code == -127 || c.code < 128) {

                sb.append(c)
            } else {
                var s: String? = ""
                try {

                    val array = PinyinHelper.toHanyuPinyinStringArray(c, format)
                    if (array.isNotEmpty()) {
                        s = array.first()
                        sb.append(s)
                    }
                } catch (e: BadHanyuPinyinOutputFormatCombination) {
                    e.printStackTrace()
                    sb.append(s)
                }
            }
        }

        return sb.toString()
    }

    override fun setListener() {
        binding.anbiiip.setTrackedOnClickListener {
            val intent = Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS)
            intent.addCategory(R.string.ޛޠޓޑޥ_D.string())
            intent.data = Uri.parse(R.string.ޙތޛޥބ_D.string((requireActivity().packageName).toString()))
            launcher.launch(intent) {
                Egac.logDebug(TAG, R.string.ދޔޏފށ_D.string())
                (requireActivity() as Jmyh).refreshUsageAccessData()
            }
        }
    }

    private fun initData() {
        orderList()
        adapter?.setData(list)
    }

    fun reverseOrder() {
        isAsc = !isAsc
        orderList()
        adapter?.setData(list)
    }

    fun setInitData(
        launcher: Hoph, type: Int = 0, isAsc: Boolean = true, needPermission: Boolean = false
    ) {
        this.launcher = launcher
        this.type = type
        this.isAsc = isAsc
        this.needPermission = needPermission
    }

    private fun checkUsageAccessSettings(context: Context): Boolean {
        val appOpsManager = context.getSystemService(Context.APP_OPS_SERVICE) as AppOpsManager

        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            appOpsManager.unsafeCheckOpNoThrow(
                AppOpsManager.OPSTR_GET_USAGE_STATS, android.os.Process.myUid(), context.packageName
            ) == AppOpsManager.MODE_ALLOWED
        } else {
            appOpsManager.checkOpNoThrow(
                AppOpsManager.OPSTR_GET_USAGE_STATS, android.os.Process.myUid(), context.packageName
            ) == AppOpsManager.MODE_ALLOWED
        }
    }

    override fun setView() {
        if (needPermission && !checkUsageAccessSettings(requireContext())) {
            binding.okpgtql.visibility = View.GONE
            binding.dfrpswo.visibility = View.VISIBLE
        } else {
            if (isRefreshData) {
                binding.dboqifh.visibility = View.GONE
            }
            initRv()
            initData()
        }
    }

    private fun otherAppRemove(appBean: Rorl) {
        (requireActivity() as Jmyh).otherPageRemove(appBean, this)
    }

    fun setDataRefresh(dataList: List<Rorl>) {

        list.clear()
        list.addAll(dataList)
        orderList()
        if (isVisible) {
            if (adapter == null) {
                initRv()
            }
            if (isRefreshData) {
                binding.dboqifh.visibility = View.GONE
            }
            adapter?.setData(list)
        }
    }

    private fun showUnInstall(selectList: List<Rorl>) {
        (requireActivity() as Jmyh).showUnInstall(selectList)
    }

    private fun initRv() {
        adapter = Dpse(itemClick = {
            if (!(requireActivity() as Jmyh).animationFinish) {
                return@Dpse
            }
            requireActivity().showAppDetailDialog(it, launcher) { unInstalled ->
                if (unInstalled) {
                    adapter?.removeData(it)
                    otherAppRemove(it)
                }
            }
        }, itemSelect = { selectList ->
            showUnInstall(selectList)
        })
        binding.hynncaa.adapter = adapter
    }
}