package pxds.etmo

import android.app.AppOpsManager
import android.app.usage.NetworkStats
import android.app.usage.NetworkStatsManager
import android.content.Context
import android.graphics.Color
import android.net.ConnectivityManager
import android.os.Build
import android.util.SparseLongArray
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.ProgressBar
import android.widget.TextView
import androidx.activity.OnBackPressedCallback
import androidx.core.util.forEach
import androidx.core.view.isVisible
import androidx.core.view.updatePadding
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.blankj.utilcode.util.AppUtils
import com.blankj.utilcode.util.BarUtils
import com.test.basd.supercleanermax.R
import com.test.basd.supercleanermax.databinding.DppktqBinding
import pxds.dlpf.buoz.fico.Ohyk
import pxds.lmmd.zmwf.Bpfw
import pxds.lmmd.zmwf.Glro
import pxds.lmmd.zmwf.Khko.setTrackedOnClickListener
import pxds.lmmd.zmwf.Khko.string
import pxds.lmmd.zmwf.Khko.toFormatSize
import pxds.lmmd.zmwf.Uawv
import pxds.lmmd.zmwf.jyyf.hwbn.wzxb.Utdc
import pxds.vazp.Ljig
import kotlin.random.Random

class Ffhe : Bpfw<DppktqBinding>() {

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

    private val AllList = mutableListOf<Ljig>()

    private var types = 2

    private var startTime = Glro.getTimesMonthmorning()

    private val mobileList = mutableListOf<Ljig>()

    private val wifiList = mutableListOf<Ljig>()

    private val mAdapter by lazy {
        class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
            val ivImage: ImageView
            val tvName: TextView
            val tvTraffic: TextView
            val wifiPro: ProgressBar
            val mobilePro: ProgressBar
            val tvstop: TextView

            init {
                ivImage = view.findViewById(R.id.jzjoluk)
                tvName = view.findViewById(R.id.hmkgyco)
                tvTraffic = view.findViewById(R.id.xlzqxyu)
                wifiPro = view.findViewById(R.id.amjrqov)
                mobilePro = view.findViewById(R.id.wbvmdnw)
                tvstop = view.findViewById(R.id.vsiplzo)
            }
        }

        object : RecyclerView.Adapter<ViewHolder>() {
            override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
                val view = LayoutInflater.from(this@Ffhe).inflate(
                    R.layout.jlifqp, parent, false
                )
                return ViewHolder(view)
            }

            override fun getItemCount() = AllList.size

            override fun onBindViewHolder(holder: ViewHolder, position: Int) {
                val c = Uawv.appList?.firstOrNull {
                    it.packageName == AllList[position].packageName
                }
                holder.ivImage.setImageDrawable(c?.icon)
                holder.tvName.text = c?.name
                holder.tvTraffic.text = (AllList[position].wifiUsed + AllList[position].mobileUsed).toFormatSize()

                holder.wifiPro.max = (AllList[0].wifiUsed + AllList[0].mobileUsed).toInt()
                holder.mobilePro.max = (AllList[0].wifiUsed + AllList[0].mobileUsed).toInt()
                holder.wifiPro.progress = (AllList[position].wifiUsed + AllList[position].mobileUsed).toInt()
                holder.mobilePro.progress = (AllList[position].mobileUsed).toInt()
                holder.tvstop.isEnabled = Glro.canStop(this@Ffhe, AllList[position].packageName)
                holder.tvstop.setTrackedOnClickListener {
                    AppUtils.launchAppDetailsSettings(AllList[position].packageName)
                }
                holder.itemView.setTrackedOnClickListener {

                }

            }

            override fun onBindViewHolder(
                holder: ViewHolder, position: Int, payloads: MutableList<Any>
            ) {
                super.onBindViewHolder(holder, position, payloads)
            }
        }
    }

    private var ifPlayAnimal = false

    private fun playLottie() {
        binding.asgxwuc.isVisible = true
        binding.aeemila.imageAssetsFolder = R.string.ޔޡޞޖޏ_D.string()
        binding.aeemila.setAnimation(R.string.ޤޡޓސރ_D.string())
        binding.aeemila.playAnimation()
        binding.root.postDelayed({
            Utdc.showInterstitialAd(this) {
                binding.asgxwuc.isVisible = false
                ifPlayAnimal=true
                hasAccessSettings()
            }
        }, Random.nextLong(2500, 4000))
    }

    private fun setData(
    ) {

        val allMobide = getNetworkStats(
            ConnectivityManager.TYPE_MOBILE, startTime, System.currentTimeMillis()
        )
        val allWifi = getNetworkStats(
            ConnectivityManager.TYPE_WIFI, startTime, System.currentTimeMillis()
        )
        AllList.clear()
        mobileList.clear()
        wifiList.clear()
        var mobileSize = 0L
        allMobide.forEach { key, value ->
            mobileSize += value
            val appPkg = packageManager.getPackagesForUid(key)
            if (appPkg?.isNotEmpty() == true) {
                val bean = Ljig(1, appPkg[0], 0, value)
                mobileList.add(bean)
            }
        }
        mobileList.sortByDescending { it.mobileUsed }
        binding.vuhemsd.text = mobileSize.toFormatSize()
        var wifi = 0L
        allWifi.forEach { key, value ->
            wifi += value
            val appPkg = packageManager.getPackagesForUid(key)
            if (appPkg?.isNotEmpty() == true) {
                val bean = Ljig(2, appPkg[0], value, 0)
                wifiList.add(bean)
            }
        }
        binding.rfaagju.text = wifi.toFormatSize()
        wifiList.sortByDescending { it.wifiUsed }

        val map = hashMapOf<String, Ljig>()
        if (types != 0) {
            for (bean in wifiList) {
                map[bean.packageName] = bean
            }
        }
        if (types != 1) {
            for (bean in mobileList) {
                if (map.containsKey(bean.packageName)) {
                    val oldBean = map[bean.packageName]
                    oldBean?.type = oldBean?.type?.plus(bean.type) ?: bean.type
                    oldBean?.mobileUsed = oldBean?.mobileUsed?.plus(bean.mobileUsed) ?: bean.mobileUsed
                    oldBean?.wifiUsed = oldBean?.wifiUsed?.plus(bean.wifiUsed) ?: bean.wifiUsed
                } else {
                    map[bean.packageName] = bean
                }
            }
        }
        for (value in map.values) {
            AllList.add(value)
        }
        AllList.sortByDescending { it.mobileUsed + it.wifiUsed }
        AllList.removeAll(AllList.filter {
            it.packageName == this.packageName
        })

        if (AllList.isNotEmpty()) {
            binding.vezjukb.isVisible = false
            binding.expzvus.run {
                layoutManager = LinearLayoutManager(context)
                adapter = mAdapter
            }
        } else {
            mAdapter.notifyDataSetChanged()
            binding.vezjukb.isVisible = true
        }

    }

    override fun initListener() {

        binding.odfxthe.setTrackedOnClickListener {
            onBackPressedDispatcher.onBackPressed()
        }
        onBackPressedDispatcher.addCallback(object : OnBackPressedCallback(true) {
            override fun handleOnBackPressed() {
                Utdc.showInterstitialAd(this@Ffhe) {
                    finishToMain()
                }
            }

        })
        binding.qwohrnn.setTrackedOnClickListener {
            checkAccesSettings(true)
        }
        binding.hyrdjsh.setTrackedOnClickListener {
            clickTop(0)
            startTime = Glro.getTimesMonthmorning()
            setData()
        }
        binding.bmruunc.setTrackedOnClickListener {
            clickTop(1)
            startTime = Glro.getNeedTime(30)
            setData()
        }
        binding.afpxctq.setTrackedOnClickListener {
            clickTop(2)
            startTime = Glro.getNeedTime(1)
            setData()
        }
        binding.wjqmpyy.setTrackedOnClickListener {
            Ohyk.showBothTypes(this) {
                when (it) {
                    0 -> {
                        binding.wjqmpyy.text = R.string.ޙޜރޑޢ_D.string()
                        types = 0
                    }

                    1 -> {
                        binding.wjqmpyy.text = R.string.ޚމގށޓ_D.string()
                        types = 1

                    }

                    2 -> {
                        binding.wjqmpyy.text = R.string.ޟޠޢޅޡ_D.string()
                        types = 2
                    }
                }
                setData()
            }
        }
    }

    private fun initList() {

        setData()

    }

    override fun onStart() {
        super.onStart()
        if (ifPlayAnimal) {
            hasAccessSettings()
        }
    }

    private fun hasAccessSettings() {
        val appOpsManager = getSystemService(Context.APP_OPS_SERVICE) as AppOpsManager
        if (
            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
            }
        ) {
            binding.lbkjdpt.isVisible = false
            initList()
        } else {
            binding.lbkjdpt.isVisible = true
        }

    }

    private fun clickTop(p: Int) {
        listOf(binding.hyrdjsh, binding.bmruunc, binding.afpxctq).forEachIndexed { index, view ->
            view.isSelected = p == index
        }

    }

    override fun initView() {
        BarUtils.setStatusBarLightMode(this, true)
        BarUtils.setStatusBarColor(this, Color.TRANSPARENT)
        binding.root.updatePadding(top = BarUtils.getStatusBarHeight())
        binding.hyrdjsh.isSelected = true
        playLottie()
    }

    fun getNetworkStats(uid: Int, start: Long, end: Long): SparseLongArray {
        val result = SparseLongArray()
        val bucket = NetworkStats.Bucket()
        try {
            val manager = this.getSystemService(Context.NETWORK_STATS_SERVICE) as NetworkStatsManager
            val stats = manager.querySummary(uid, null, start, end)
            while (stats.hasNextBucket()) {
                stats.getNextBucket(bucket)
                val currentUid = bucket.uid
                val txBytes = bucket.txBytes
                val rxBytes = bucket.rxBytes
                val totalBytes = txBytes + rxBytes
                val existingBytes = result[currentUid, 0]
                if (existingBytes == 0L) {
                    result.put(currentUid, totalBytes)
                } else {
                    result.put(currentUid, totalBytes + existingBytes)
                }
            }
            var b = 0L
            result.forEach { key, value ->
                val a = packageManager.getPackagesForUid(key)
                if (a?.isNotEmpty() == true) {
                    b += value
                }
            }
            stats.close()
        } catch (_: Exception) {
        }
        return result
    }
}