package pxds.etmo

import android.app.AppOpsManager
import android.app.usage.UsageEvents
import android.app.usage.UsageStats
import android.app.usage.UsageStatsManager
import android.content.Context
import android.content.Intent
import android.content.pm.ApplicationInfo
import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.provider.Settings
import android.view.View
import androidx.activity.addCallback
import androidx.core.view.isVisible
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.lifecycleScope
import androidx.viewpager2.adapter.FragmentStateAdapter
import com.google.android.material.tabs.TabLayoutMediator
import com.test.basd.supercleanermax.R
import com.test.basd.supercleanermax.databinding.GyqvnkBinding
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import org.json.JSONObject
import pxds.czbe.twvj.Kaxp
import pxds.czbe.twvj.Rqom
import pxds.lmmd.zmwf.Bpfw
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.Onaw.TODAY_QUERY
import pxds.lmmd.zmwf.Onaw.YESTERDAY_QUERY
import pxds.lmmd.zmwf.Onaw.timePair
import pxds.lmmd.zmwf.jyyf.hwbn.wzxb.Utdc
import pxds.lmmd.zmwf.swym.fqqm.Jenw
import pxds.lmmd.zmwf.swym.fqqm.Txzi
import pxds.vazp.Rorl

class Ngma : Bpfw<GyqvnkBinding>() {

    private lateinit var context: Context

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

    private var dataList = ArrayList<Rorl>()

    private val pages = arrayListOf<Fragment>()

    private lateinit var tabs: Array<String>

    private val TAG = R.string.ކމޢވޒ_D.string()

    private lateinit var launcher: Hoph

    private lateinit var pagerAdapter: ScreenSlidePagerAdapter

    override val isLightMode = true

    fun changeTimeRefresh(queryTime: Int, fragmentPosition: Int) {
        lifecycleScope.launch(Dispatchers.IO) {
            initAppData()

            setLaunchesData(queryTime)

            setScreenTimeData(queryTime)

            launch(Dispatchers.Main) { updateFragmentData(fragmentPosition) }
        }
    }

    private fun intData() {

        CoroutineScope(Dispatchers.IO).launch {

            initAppData()

            setLaunchesData()

            setScreenTimeData()

            launch(Dispatchers.Main) {
                updateFragmentData(0, 1)
            }
        }
    }

    private fun setScreenTimeData(queryTime: Int = TODAY_QUERY) {
        val pair = timePair(queryTime)

        val screenTimeMap = Jenw(pair.first, pair.second).run(context)

        dataList.forEach { app ->
            if (screenTimeMap.keys.contains(app.pkg)) {
                val value = screenTimeMap[app.pkg]
                value?.let { b ->
                    app.screenTime = b.c
                }
            }
        }
    }

    private fun checkUsageAccessSettings(): Boolean {

        val appOpsManager = 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(), this.packageName
            ) == AppOpsManager.MODE_ALLOWED
        } else {
            appOpsManager.checkOpNoThrow(
                AppOpsManager.OPSTR_GET_USAGE_STATS, android.os.Process.myUid(), this.packageName
            ) == AppOpsManager.MODE_ALLOWED
        }
    }

    fun getEventList2(
        context: Context, startTime: Long, endTime: Long, ): HashMap<String, ArrayList<UsageEvents.Event>> {

        val mUsmManager = context.getSystemService(Context.USAGE_STATS_SERVICE) as UsageStatsManager

        val allList = ArrayList<UsageEvents.Event>()

        try {
            val events = mUsmManager.queryEvents(startTime, endTime)
            while (events.hasNextEvent()) {
                val event = UsageEvents.Event()
                events.getNextEvent(event)

                val flag2 = (event.eventType != UsageEvents.Event.ACTIVITY_STOPPED) && (event.eventType != UsageEvents.Event.STANDBY_BUCKET_CHANGED)
                if (flag2) {
                    allList.add(event)
                }
            }
        } catch (e: Exception) {
            Egac.logDebug(TAG, R.string.ޜދހޒޣ_D.string((e.printStackTrace()).toString()))
            e.printStackTrace()
        }

        val hashMap = HashMap<String, ArrayList<UsageEvents.Event>>()

        allList.forEachIndexed { index, event ->

            val list = hashMap[event.packageName]
            if (list == null) {
                hashMap[event.packageName] = arrayListOf()
            }

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

            if (lastEvent != null && lastEvent.packageName != event.packageName) {
                list?.add(lastEvent)
            }

            list?.add(event)

        }

        return hashMap
    }

    private fun getAppUseAnalyze(
        context: Context, queryTime: Int = YESTERDAY_QUERY, dataList: List<Rorl>, ): ArrayList<Rorl> {
        val launchList = arrayListOf<Rorl>()
        val pair = timePair(queryTime)
        val startTime: Long = pair.first
        val endTime: Long = pair.second

        val stateList = getUsageList(context, startTime, endTime)
        val evenMap = getEventList2(context, startTime, endTime)

        dataList.forEach { app ->

            app.usageEvents = evenMap[app.pkg]?.filter { it.eventType == 19 }
            app.usageStats = stateList.filter { it.packageName == app.pkg }
        }

        launchList.addAll(dataList)

        return launchList
    }

    override fun initView() {
        launcher = Hoph(this)
        context = this
        initPage()
        intTab()
        if (checkUsageAccessSettings()) {

            intData()
        } else {
            binding.ziihecw.visibility = View.GONE
            binding.dfrpswo.visibility = View.VISIBLE
        }
        playLottie()
    }

    inner class ScreenSlidePagerAdapter(fa: FragmentActivity) : FragmentStateAdapter(fa) {
        override fun getItemCount(): Int = pages.size
        override fun createFragment(position: Int): Fragment = pages[position]
    }

    private fun playLottie(showFinish: (() -> Unit)? = null) {
        binding.ekqopho.isVisible = true
        binding.bawmlwn.imageAssetsFolder = R.string.ޞސޔޅޚ_D.string()
        binding.bawmlwn.setAnimation(R.string.ފތލތދ_D.string())
        binding.bawmlwn.playAnimation()
        binding.root.postDelayed({
            Utdc.showInterstitialAd(this) {
                binding.ekqopho.isVisible = false
                showFinish?.invoke()
            }
        }, 6000)
    }

    private fun setAppInstallTime(appBean: Rorl, context: Context) {

        var firstInstallTime = 0L
        try {
            val packageManager = context.packageManager
            val packageInfo: PackageInfo = packageManager.getPackageInfo(appBean.pkg, 0)

            firstInstallTime = packageInfo.firstInstallTime

            val lastUpdateTime = packageInfo.lastUpdateTime

        } catch (e: PackageManager.NameNotFoundException) {
            e.printStackTrace()
        }

        appBean.installTime = firstInstallTime
    }

    private fun isLaunchApp(context: Context, app: PackageInfo, filterSystem: Boolean = true): Boolean {

        val flagSystem = (app.applicationInfo.flags and ApplicationInfo.FLAG_SYSTEM) < 1
        val flag = if (filterSystem) flagSystem else true

        return flag && app.applicationInfo.packageName != context.packageName
    }

    private fun intTab() {

        tabs = arrayOf(R.string.ޠޒޤކނ_D.string(), R.string.ޛސޗޥސ_D.string())
        TabLayoutMediator(binding.hstsurf, binding.gstuqfj) { tab, position ->
            tab.text = tabs[position]
            binding.gstuqfj.currentItem = position
        }.attach()

        binding.gstuqfj.currentItem = 0
    }

    private fun initPage() {
        pages.add(Rqom())
        pages.add(Kaxp())
        pagerAdapter = ScreenSlidePagerAdapter(this)
        binding.gstuqfj.adapter = pagerAdapter
    }

    private fun updateFragmentData(vararg position: Int) {
        if (position.contains(0)) {
            val launchesFragment = pages[0] as Rqom
            launchesFragment.setAppUseData(dataList)
        }

        if (position.contains(1)) {
            val screenTimeFragment = pages[1] as Kaxp
            screenTimeFragment.setScreenData(dataList)
        }

    }

    private fun initAppData() {
        dataList.clear()

        val pm = packageManager
        val packages = pm.getInstalledPackages(0)

        packages.forEach { app ->
            if (isLaunchApp(context, app)) {

                val appBean = Rorl(
                    app.applicationInfo.loadIcon(pm), app.applicationInfo.loadLabel(pm).toString(), app.applicationInfo.packageName, false
                )

                setAppInstallTime(appBean, context)
                dataList.add(appBean)
            }
        }

    }

    override fun initListener() {
        binding.ngdqagq.setTrackedOnClickListener {
            Utdc.showInterstitialAd(this) {
               finishToMain()
            }
        }
        onBackPressedDispatcher.addCallback {
            Egac.logDebug(TAG, R.string.ހޔފޥލ_D.string())
            Utdc.showInterstitialAd(this@Ngma) {
                finishToMain()
            }
        }
        binding.djnahze.setTrackedOnClickListener {
            val intent = Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS)
            intent.addCategory(R.string.ޛޠޓޑޥ_D.string())
            intent.data = Uri.parse(R.string.ޙތޛޥބ_D.string((context.packageName).toString()))
            launcher.launch(intent) {
                Egac.logDebug(TAG, R.string.ދޔޏފށ_D.string())
                val obj = JSONObject()
                obj.put(R.string.ޓޞޜޅމ_D.string(), javaClass.simpleName)

                if (checkUsageAccessSettings()) {
                    binding.dfrpswo.visibility = View.GONE
                    binding.ziihecw.visibility = View.VISIBLE
                    intData()
                } else {
                    finishToMain()
                }
            }
        }
    }

    private fun setLaunchesData(queryTime: Int = TODAY_QUERY) {
        val tempList = arrayListOf<Rorl>()
        tempList.addAll(dataList)

        dataList = getAppUseAnalyze(context, queryTime, tempList)

        val pair = timePair(queryTime)
        val ast = Txzi(pair.first, pair.second)
        val hashMap = ast.run(context)
        dataList.forEach { app ->
            if (hashMap.keys.contains(app.pkg)) {
                val value = hashMap[app.pkg]
                if (value != null) {
                    val tempList2 = arrayListOf<UsageEvents.Event>()
                    tempList2.addAll(value)
                    app.usageEvents?.also { evens -> tempList2.addAll(evens) }
                    app.usageEvents = tempList2
                }
            }
        }
    }

    fun getUsageList(context: Context, startTime: Long, endTime: Long): ArrayList<UsageStats> {
        val list = arrayListOf<UsageStats>()
        val mUsmManager = context.getSystemService(Context.USAGE_STATS_SERVICE) as UsageStatsManager
        val map = mUsmManager.queryAndAggregateUsageStats(startTime, endTime)
        map.values.forEach { stats ->
            if (stats.totalTimeInForeground > 0) {
                list.add(stats)
            } else {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                    if (stats.totalTimeForegroundServiceUsed > 0) {
                        list.add(stats)
                    }
                }
            }

        }
        return list
    }
}