package pxds.etmo

import android.app.AppOpsManager
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.view.View
import androidx.activity.addCallback
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
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 androidx.viewpager2.widget.ViewPager2
import com.test.basd.supercleanermax.R
import com.test.basd.supercleanermax.databinding.UjeoizBinding
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.cancel
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.json.JSONObject
import pxds.czbe.twvj.Roik
import pxds.czbe.twvj.Roik.Companion.APP_LIST_TYPE_INSTALL
import pxds.czbe.twvj.Roik.Companion.APP_LIST_TYPE_LAST_USE
import pxds.czbe.twvj.Roik.Companion.APP_LIST_TYPE_NAME
import pxds.czbe.twvj.Roik.Companion.APP_LIST_TYPE_SIZE
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.THIRTY_DAYS_QUERY
import pxds.lmmd.zmwf.Onaw.timePair
import pxds.lmmd.zmwf.Tqzu
import pxds.lmmd.zmwf.jyyf.hwbn.wzxb.Utdc
import pxds.vazp.Rorl
import java.util.concurrent.LinkedBlockingDeque

class Jmyh : Bpfw<UjeoizBinding>() {

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

    private val pages = arrayListOf<Fragment>()

    private lateinit var context: Context

    private val dataList = ArrayList<Rorl>()

    private var currentPosition: Int = 0

    private lateinit var launcher: Hoph

    private val TAG: String = R.string.ޅޥޕބޥ_D.string()

    private lateinit var pagerAdapter: ScreenSlidePagerAdapter

    var animationFinish: Boolean = false

    override val isLightMode = true

    fun showUnInstall(selectList: List<Rorl>) {

        if (selectList.isNotEmpty()) {
            binding.mrsyiad.isVisible = true
            binding.mrsyiad.text = R.string.ޤއށޣގ_D.string((selectList.size).toString())
            binding.mrsyiad.setTrackedOnClickListener {
                binding.mrsyiad.isVisible = false
                binding.mrsyiad.setTrackedOnClickListener { }
                unInstallApps(selectList) { unInstalled ->
                    allPageRemove(unInstalled)
                }
            }
        } else {
            binding.mrsyiad.isVisible = false
            binding.mrsyiad.setTrackedOnClickListener { }
        }

    }

    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
    }

    companion object {

    }

    private fun changeAsc(position: Int, isAsc: Boolean) {
        when (position) {
            0 -> {
                binding.zoavawj.setAscOrder(false)
                binding.jupfysh.setAscOrder(false)
                binding.npjdnhx.setAscOrder(false)

                binding.osszwic.setAscOrder(true, isAsc)
            }

            1 -> {
                binding.osszwic.setAscOrder(false)
                binding.jupfysh.setAscOrder(false)
                binding.npjdnhx.setAscOrder(false)

                binding.zoavawj.setAscOrder(true, isAsc)
            }

            2 -> {
                binding.osszwic.setAscOrder(false)
                binding.zoavawj.setAscOrder(false)
                binding.npjdnhx.setAscOrder(false)

                binding.jupfysh.setAscOrder(true, isAsc)
            }

            3 -> {
                binding.osszwic.setAscOrder(false)
                binding.zoavawj.setAscOrder(false)
                binding.jupfysh.setAscOrder(false)

                binding.npjdnhx.setAscOrder(true, isAsc)
            }
        }
    }

    private fun allPageRemove(unInstalled: List<Rorl>) {

        dataList.removeAll(unInstalled.toSet())

        pages.forEachIndexed { index, fragment ->
            val fg = fragment as Roik
            if (index == currentPosition) {

                lifecycleScope.launch(Dispatchers.Main) {
                    delay(1500)
                    fg.setDataRefresh(dataList)
                }
            } else {

                fg.setData(dataList)
            }
        }
    }

    override fun initView() {
        context = this
        launcher = Hoph(this)
        setContentView(binding.root)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.fosyiss)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }

        initViewPager()
        playLottie()
        CoroutineScope(Dispatchers.Main).launch {

            initAppData()

            if (checkUsageAccessSettings()) {
                async(Dispatchers.IO) {
                    setAppBeanSize()
                    setAppLastUseTime()
                }.await()
            }

            pages.forEachIndexed { index, fragment ->
                val appListFragment = (fragment as Roik)
                appListFragment.refreshFragmentData(dataList, index == currentPosition)
            }
        }

        binding.mselzwj.setTrackedOnClickListener {
            if (currentPosition == 0) {
                val fragment = (pages[0] as Roik)
                fragment.reverseOrder()
                val isAsc = fragment.isAsc
                changeAsc(0, isAsc)
            }
            binding.gstuqfj.setCurrentItem(0, false)
        }
        binding.kldphlm.setTrackedOnClickListener {
            if (currentPosition == 1) {
                val fragment = (pages[1] as Roik)
                fragment.reverseOrder()
                val isAsc = fragment.isAsc
                changeAsc(1, isAsc)
            }
            binding.gstuqfj.setCurrentItem(1, false)
        }
        binding.udpyhoi.setTrackedOnClickListener {
            if (currentPosition == 2) {
                val fragment = (pages[2] as Roik)
                fragment.reverseOrder()
                val isAsc = fragment.isAsc
                changeAsc(2, isAsc)
            }
            binding.gstuqfj.setCurrentItem(2, false)
        }
        binding.jfwuual.setTrackedOnClickListener {
            if (currentPosition == 3) {
                val fragment = (pages[3] as Roik)
                fragment.reverseOrder()
                val isAsc = fragment.isAsc
                changeAsc(3, isAsc)
            }
            binding.gstuqfj.setCurrentItem(3, false)
        }
        binding.ngdqagq.setTrackedOnClickListener {
            Utdc.showInterstitialAd(this) {
                finishToMain()
            }
        }
        onBackPressedDispatcher.addCallback {
            Utdc.showInterstitialAd(this@Jmyh) {
                finishToMain()
            }
        }

    }

    private fun setAppBeanSize() {
        dataList.forEach { app ->
            val size = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                Tqzu.instance?.getAppSizeO(context, app.pkg)
            } else {
                Tqzu.instance?.getAppSize(context, app.pkg)
            }
            app.appSize = size ?: 0
        }
    }

    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)
            }
        }
        Egac.logDebug(TAG, R.string.ޟވޥވބ_D.string((dataList.size).toString()))
    }

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

    private 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
    }

    private fun isInstalled(context: Context, pkg: String, error: (() -> Unit)? = null): Boolean {
        return try {
            context.packageManager.getPackageInfo(pkg, 0)
            true
        } catch (e: Exception) {
            error?.invoke()
            false
        }
    }

    fun otherPageRemove(appBean: Rorl, fragment: Roik) {
        dataList.remove(appBean)
        pages.forEach {
            if (it != fragment) {
                (it as Roik).setData(dataList)
            }
        }
    }

    private fun unInstallApps(selectList: List<Rorl>, finishUnInstall: (unInstalled: List<Rorl>) -> Unit) = lifecycleScope.launch(Dispatchers.IO) {

            val unInstall = arrayListOf<Rorl>()
            unInstall.addAll(selectList)

            val unInstalled = arrayListOf<Rorl>()

            val queue = LinkedBlockingDeque<Rorl>()

            val first = unInstall[0]
            queue.put(first)

            while (isActive) {
                val appBean = withContext(Dispatchers.IO) {
                    queue.take()
                }
                delay(250)
                Egac.logDebug(TAG, R.string.ޙޗށޅއ_D.string())
                val intent = Intent(Intent.ACTION_DELETE, Uri.parse(R.string.ޙތޛޥބ_D.string((appBean.pkg).toString())))

                launcher.launch(intent) {

                    val flag = isInstalled(
                        this@Jmyh, appBean.pkg, error = {
                            unInstall.remove(appBean)
                            unInstalled.add(appBean)
                        })

                    if (!flag) {
                        unInstalled.add(appBean)
                    }
                    unInstall.remove(appBean)

                    if (unInstall.isNotEmpty()) {
                        val next = unInstall[0]
                        Egac.logDebug(TAG, R.string.ޘދގޅތ_D.string((next).toString()))
                        queue.put(next)
                    } else {
                        Egac.logDebug(TAG, R.string.ނހޞއދ_D.string((unInstalled).toString()))
                        finishUnInstall.invoke(unInstalled)
                        cancel()
                    }
                }
            }

        }

    private fun initViewPager() {
        pages.add(Roik().apply { setInitData(launcher, APP_LIST_TYPE_NAME, true) })
        pages.add(Roik().apply { setInitData(launcher, APP_LIST_TYPE_INSTALL, false) })
        pages.add(Roik().apply { setInitData(launcher, APP_LIST_TYPE_SIZE, false, needPermission = true) })
        pages.add(Roik().apply { setInitData(launcher, APP_LIST_TYPE_LAST_USE, false, needPermission = true) })

        pagerAdapter = ScreenSlidePagerAdapter(this@Jmyh)

        binding.gstuqfj.adapter = pagerAdapter

        binding.gstuqfj.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
            override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {
                super.onPageScrolled(position, positionOffset, positionOffsetPixels)
                currentPosition = position
                changeIndicator(position)
                val fragment = (pages[position] as Roik)
                fragment.setDataRefresh(dataList)
                changeAsc(position, fragment.isAsc)
            }
        })
    }

    private fun setAppLastUseTime(
        queryTime: Int = THIRTY_DAYS_QUERY
    ) {
        val pair = timePair(queryTime)
        val startTime: Long = pair.first
        val endTime: Long = pair.second

        val usageList = getUsageList(context, startTime, endTime)

        dataList.forEach { app ->
            val filterList = usageList.filter { it.packageName == app.pkg }
            app.usageStats = filterList
            app.lastUsedTime = if (filterList.isNotEmpty()) filterList.maxOf { it.lastTimeUsed } else -2
        }
    }

    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 refreshUsageAccessData() {
        val obj = JSONObject()
        obj.put(R.string.ޓޞޜޅމ_D.string(), javaClass.simpleName)

        if (checkUsageAccessSettings()) {

            pages.forEachIndexed { index, fragment ->
                val appListFragment = (fragment as Roik)
                appListFragment.showContent(index == currentPosition)
            }
            lifecycleScope.launch(Dispatchers.IO) {

                setAppBeanSize()
                setAppLastUseTime()

                launch(Dispatchers.Main) {
                    pages.forEachIndexed { index, fragment ->
                        val appListFragment = (fragment as Roik)
                        appListFragment.refreshFragmentData(dataList, index == currentPosition, index)
                    }
                }
            }
        }
    }

    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 changeIndicator(position: Int) {
        when (position) {
            0 -> {
                binding.tqtktgm.visibility = View.VISIBLE
                binding.chrfcar.visibility = View.INVISIBLE
                binding.sdswwhp.visibility = View.INVISIBLE
                binding.jxwffxz.visibility = View.INVISIBLE
            }

            1 -> {
                binding.tqtktgm.visibility = View.INVISIBLE
                binding.chrfcar.visibility = View.VISIBLE
                binding.sdswwhp.visibility = View.INVISIBLE
                binding.jxwffxz.visibility = View.INVISIBLE
            }

            2 -> {
                binding.tqtktgm.visibility = View.INVISIBLE
                binding.chrfcar.visibility = View.INVISIBLE
                binding.sdswwhp.visibility = View.VISIBLE
                binding.jxwffxz.visibility = View.INVISIBLE
            }

            3 -> {
                binding.tqtktgm.visibility = View.INVISIBLE
                binding.chrfcar.visibility = View.INVISIBLE
                binding.sdswwhp.visibility = View.INVISIBLE
                binding.jxwffxz.visibility = View.VISIBLE
            }
        }
    }

    private fun playLottie() {
        Egac.logDebug(TAG, R.string.ޑޓވބބ_D.string())
        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) {
                animationFinish = true
                binding.ekqopho.isVisible = false
            }
        }, 6000)
    }
}

