package pxds.czbe.twvj

import android.app.usage.UsageEvents
import android.app.usage.UsageEvents.Event.ACTIVITY_PAUSED
import android.app.usage.UsageEvents.Event.ACTIVITY_RESUMED
import android.app.usage.UsageEvents.Event.FOREGROUND_SERVICE_START
import android.graphics.Typeface
import android.os.Bundle
import android.view.View
import androidx.core.content.ContextCompat
import com.test.basd.supercleanermax.R
import com.test.basd.supercleanermax.databinding.LmvsuzBinding
import pxds.dlpf.buoz.fico.Wncp.showTimeSelectDialog
import pxds.etmo.Ngma
import pxds.hpls.xkxo.Fito
import pxds.lmmd.zmwf.Egac
import pxds.lmmd.zmwf.Khko.setTrackedOnClickListener
import pxds.lmmd.zmwf.Khko.string
import pxds.lmmd.zmwf.Onaw
import pxds.lmmd.zmwf.Onaw.PAST_60_MINUS_QUERY
import pxds.lmmd.zmwf.Onaw.SEVEN_DAYS_QUERY
import pxds.lmmd.zmwf.Onaw.TODAY_QUERY
import pxds.lmmd.zmwf.Onaw.YESTERDAY_QUERY
import pxds.lmmd.zmwf.Wecj
import pxds.vazp.Rorl
import java.text.SimpleDateFormat
import kotlin.time.Duration.Companion.hours
import kotlin.time.DurationUnit

class Rqom : Wecj<LmvsuzBinding>() {

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

    private var dataList = arrayListOf<Rorl>()

    private lateinit var adapter: Fito

    private var UI_MODE = UI_MODE_ALL

    private val TAG = R.string.ޣބޔރޅ_D.string()

    private var simpleDateFormat2 = SimpleDateFormat(R.string.އށބސސ_D.string())

    fun recent60UI(isReFresh: Boolean = true) {
        binding.dwjlpjd.text = R.string.ގނފގޒ_D.string()
        if (isReFresh) {
            (requireActivity() as Ngma).changeTimeRefresh(PAST_60_MINUS_QUERY, 0)
        }
    }

    fun launchesMode() {
        foregroundEnable(false)
        backgroundEnable(false)
        launchesEnable(true)
        UI_MODE = UI_MODE_ALL
        filterRv()
    }

    fun todayUI(isReFresh: Boolean = true) {
        binding.dwjlpjd.text = R.string.ކޣނޤޥ_D.string() + simpleDateFormat2.format(System.currentTimeMillis())
        if (isReFresh) {
            (requireActivity() as Ngma).changeTimeRefresh(TODAY_QUERY, 0)
        }
    }

    private fun setLaunchNumber() {

        val tempList = ArrayList<UsageEvents.Event>()

        dataList.forEach { app ->

            app.usageEvents?.let { events ->

                tempList.clear()
                tempList.addAll(events)

                tempList.forEachIndexed { index, event ->

                    if (app.pkg == R.string.ގޕޠވޥ_D.string()) {
                        Egac.logDebug(
                            TAG, R.string.ވޓޅދލ_D.string((index).toString(), (event.packageName).toString()) +
                                    Onaw.simpleDateFormat.format(event.timeStamp) +
                                    R.string.ޢޚބލޣ_D.string((event.eventType).toString())
                        )
                    }

                    if (event.eventType == FOREGROUND_SERVICE_START) {
                        app.backgroundTimes++
                    }

                    val lastIndex = index - 1
                    var lastEvent: UsageEvents.Event? = null
                    if (lastIndex >= 0) {
                        lastEvent = tempList[lastIndex]
                    }

                    if (event.eventType == ACTIVITY_RESUMED) {

                        val flag1 = lastEvent == null || ((lastEvent.packageName != app.pkg) && (lastEvent.eventType == ACTIVITY_PAUSED))
                        val flag2 = (lastEvent != null) && (lastEvent.packageName != app.pkg)

                        if (flag1) {
                            app.foregroundTimes++

                            if (app.pkg == R.string.ގޕޠވޥ_D.string()) {
                                Egac.logDebug(TAG, R.string.ޛޛޚޡޜ_D.string((app.foregroundTimes).toString()))
                            }

                        } else if (flag2) {
                            app.foregroundTimes++

                            if (app.pkg == R.string.ގޕޠވޥ_D.string()) {
                                Egac.logDebug(TAG, R.string.ޠނއހޥ_D.string((app.foregroundTimes).toString()))
                            }
                        }
                    }
                }
            }

            if (app.foregroundTimes < 2) {
                app.foregroundTimes = 0
            }
            app.launchTimes = app.foregroundTimes + app.backgroundTimes

            if (app.pkg == R.string.ގޕޠވޥ_D.string()) {
                Egac.logDebug(
                    TAG, R.string.ވޏޥޕޠ_D.string((app.pkg).toString(), (app.launchTimes).toString()) +
                            R.string.ރމދޡޓ_D.string((app.foregroundTimes).toString()) +
                            R.string.ޜފޟޚތ_D.string((app.backgroundTimes).toString())
                )
            }

        }

        val totalNumber = dataList.sumOf { it.launchTimes }
        val foregroundNumber = dataList.sumOf { it.foregroundTimes }
        val backgroundNumber = dataList.sumOf { it.backgroundTimes }

        binding.tmquqxv.text = totalNumber.toString()
        binding.hornvcx.text = foregroundNumber.toString()
        binding.vnoqfec.text = backgroundNumber.toString()
    }

    override fun setListener() {
        binding.oasfpim.setTrackedOnClickListener {
            launchesMode()
        }

        binding.vsovrmb.setTrackedOnClickListener {
            foregroundMode()
        }

        binding.gxysaug.setTrackedOnClickListener {
            backgroundMode()
        }
        binding.wifbgxg.setTrackedOnClickListener {
            requireContext().showTimeSelectDialog {
                when (it) {
                    PAST_60_MINUS_QUERY -> {
                        recent60UI()
                    }

                    TODAY_QUERY -> {
                        todayUI()
                    }

                    YESTERDAY_QUERY -> {
                        yesterdayUI()
                    }

                    SEVEN_DAYS_QUERY -> {
                        sevenDaysUI()
                    }
                }
            }
        }

        todayUI(false)
    }

    companion object {
        const val UI_MODE_ALL = 5
        const val UI_MODE_FOREGROUND = 25
        const val UI_MODE_BACKGROUND = 35
    }

    fun backgroundEnable(enable: Boolean) {
        if (enable) {
            val enableBorder = ContextCompat.getDrawable(requireContext(), R.drawable.iaqrhwqf)
            binding.wvziidz.background = enableBorder
            binding.jrnvzbw.visibility = View.VISIBLE
            binding.vnoqfec.setTextColor(
                ContextCompat.getColor(
                    requireContext(), R.color.ޖޙފޗއ
                )
            )
            binding.rxqhjsd.setTextColor(
                ContextCompat.getColor(
                    requireContext(), R.color.ޖޙފޗއ
                )
            )
        } else {
            val disableBorder = ContextCompat.getDrawable(requireContext(), R.drawable.fkrxpjle)
            binding.wvziidz.background = disableBorder
            binding.jrnvzbw.visibility = View.GONE
            binding.vnoqfec.setTextColor(
                ContextCompat.getColor(
                    requireContext(), R.color.ޏށވޢރ
                )
            )
            binding.rxqhjsd.setTextColor(
                ContextCompat.getColor(
                    requireContext(), R.color.ފއބޑޒ
                )
            )
        }
    }

    fun yesterdayUI(isReFresh: Boolean = true) {
        binding.dwjlpjd.text = R.string.ދޏގށޜ_D.string() + simpleDateFormat2.format(System.currentTimeMillis() - 24.hours.toLong(DurationUnit.MILLISECONDS))
        if (isReFresh) {
            (requireActivity() as Ngma).changeTimeRefresh(YESTERDAY_QUERY, 0)
        }
    }

    fun setAppUseData(dataList: List<Rorl>) {
        Egac.logDebug(TAG, R.string.ށތޖޠޟ_D.string())
        this.dataList.clear()
        this.dataList.addAll(dataList)

        if (isVisible) {
            setLaunchNumber2()
            launchesMode()
        }
    }

    fun foregroundEnable(enable: Boolean) {
        if (enable) {
            val enableBorder = ContextCompat.getDrawable(requireContext(), R.drawable.iaqrhwqf)
            binding.exfiwum.background = enableBorder
            binding.boyguht.visibility = View.VISIBLE
            binding.hornvcx.setTextColor(
                ContextCompat.getColor(
                    requireContext(), R.color.ޖޙފޗއ
                )
            )
            binding.pfdixtf.setTextColor(
                ContextCompat.getColor(
                    requireContext(), R.color.ޖޙފޗއ
                )
            )
        } else {
            val disableBorder = ContextCompat.getDrawable(requireContext(), R.drawable.fkrxpjle)
            binding.exfiwum.background = disableBorder
            binding.boyguht.visibility = View.GONE
            binding.hornvcx.setTextColor(
                ContextCompat.getColor(
                    requireContext(), R.color.ޏށވޢރ
                )
            )
            binding.pfdixtf.setTextColor(
                ContextCompat.getColor(
                    requireContext(), R.color.ފއބޑޒ
                )
            )
        }
    }

    fun launchesEnable(enable: Boolean) {
        if (enable) {
            val enableBorder = ContextCompat.getDrawable(requireContext(), R.drawable.iaqrhwqf)
            binding.fpbwqfu.background = enableBorder
            binding.xqsjomb.visibility = View.VISIBLE
            binding.tmquqxv.setTextColor(
                ContextCompat.getColor(
                    requireContext(), R.color.ޖޙފޗއ
                )
            )
            binding.fkwqcnn.setTextColor(ContextCompat.getColor(requireContext(), R.color.ޖޙފޗއ))
        } else {
            val disableBorder = ContextCompat.getDrawable(requireContext(), R.drawable.fkrxpjle)
            binding.fpbwqfu.background = disableBorder
            binding.xqsjomb.visibility = View.GONE
            binding.tmquqxv.setTextColor(
                ContextCompat.getColor(
                    requireContext(), R.color.ޏށވޢރ
                )
            )
            binding.fkwqcnn.setTextColor(
                ContextCompat.getColor(
                    requireContext(), R.color.ފއބޑޒ
                )
            )
        }
    }

    override fun setView() {
        setTextFont()
        adapter = Fito(requireActivity(), Fito.UI_LAUNCHES_MODE)
        binding.hynncaa.adapter = adapter
    }

    private fun setTextFont() {
        val fontMedium = R.string.ޜޢޔޒޞ_D.string()
        val fontMediumTypeface = Typeface.create(fontMedium, Typeface.NORMAL)
        binding.dwjlpjd.setTypeface(fontMediumTypeface)
    }

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

    fun backgroundMode() {
        launchesEnable(false)
        foregroundEnable(false)
        backgroundEnable(true)
        UI_MODE = UI_MODE_BACKGROUND
        filterRv()
    }

    private fun setLaunchNumber2() {
        dataList.forEach { app ->
            app.foregroundTimes = app.usageEvents?.filter { it.eventType == 1 }?.size ?: 0
            app.backgroundTimes = app.usageEvents?.filter { it.eventType == 19 }?.size ?: 0
            app.launchTimes = app.foregroundTimes + app.backgroundTimes
        }

        val totalNumber = dataList.sumOf { it.launchTimes }
        val foregroundNumber = dataList.sumOf { it.foregroundTimes }
        val backgroundNumber = dataList.sumOf { it.backgroundTimes }

        binding.tmquqxv.text = totalNumber.toString()
        binding.hornvcx.text = foregroundNumber.toString()
        binding.vnoqfec.text = backgroundNumber.toString()
    }

    fun sevenDaysUI(isReFresh: Boolean = true) {
        binding.dwjlpjd.text = R.string.ޟޢޟވޙ_D.string()
        if (isReFresh) {
            (requireActivity() as Ngma).changeTimeRefresh(SEVEN_DAYS_QUERY, 0)
        }
    }

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

    }

    fun foregroundMode() {
        launchesEnable(false)
        backgroundEnable(false)
        foregroundEnable(true)
        UI_MODE = UI_MODE_FOREGROUND
        filterRv()
    }

    private fun filterRv() {
        adapter.setNumberMode(UI_MODE)
        when (UI_MODE) {
            UI_MODE_ALL -> {
                val data = dataList.filter { it.launchTimes > 0 }
                adapter.setData(data)
            }

            UI_MODE_FOREGROUND -> {
                val data = dataList.filter { it.foregroundTimes > 0 }
                adapter.setData(data)
            }

            UI_MODE_BACKGROUND -> {
                val data = dataList.filter { it.backgroundTimes > 0 }
                adapter.setData(data)
            }
        }
    }
}