package pxds.etmo

import android.animation.ValueAnimator
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Color
import android.view.LayoutInflater
import android.view.ViewGroup
import android.view.animation.LinearInterpolator
import androidx.activity.OnBackPressedCallback
import androidx.core.view.isVisible
import androidx.core.view.updatePadding
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.BarUtils
import com.test.basd.supercleanermax.R
import com.test.basd.supercleanermax.databinding.FigdseBinding
import com.test.basd.supercleanermax.databinding.MkisvqBinding
import com.test.basd.supercleanermax.databinding.TpxakgBinding
import pokercc.android.expandablerecyclerview.ExpandableAdapter
import pxds.dlpf.buoz.fico.Dsce
import pxds.lmmd.zmwf.Bpfw
import pxds.lmmd.zmwf.Khko.setTrackedOnClickListener
import pxds.lmmd.zmwf.Khko.string
import pxds.lmmd.zmwf.Khko.toFormatSize
import pxds.lmmd.zmwf.Oejm
import pxds.lmmd.zmwf.jyyf.hwbn.wzxb.Utdc
import pxds.vazp.ChildBean
import pxds.vazp.Qsgj

class Bihk : Bpfw<FigdseBinding>() {

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

    private val parentList by lazy {
        mutableListOf(
            Qsgj(
                title = R.string.ނޚފޖދ_D.string(), childItem = child3, parentSize = sizes[0], isParentSelected = true, expanded = false
            ), Qsgj(
                title = R.string.ސޓޕޅޟ_D.string(), childItem = child4, parentSize = sizes[1], isParentSelected = true, expanded = false
            ), Qsgj(
                title = R.string.ޝޛސޑޢ_D.string(), childItem = child5, parentSize = sizes[2], isParentSelected = true, expanded = false
            )
        )
    }

    private val sizes = MutableList(3) { 0L }

    private val selectList = mutableListOf<String>()

    private var selectSize = 0L

    private var ScanCount = 0

    private val child1 = ArrayList<ChildBean>()

    private val mAdapter by lazy {
        class ParentViewHolder(val binding: MkisvqBinding) : ExpandableAdapter.ViewHolder(binding.root)

        class ChildViewHolder(val binding: TpxakgBinding) : ExpandableAdapter.ViewHolder(binding.root)

        object : ExpandableAdapter<ExpandableAdapter.ViewHolder>() {
            override fun getChildCount(groupPosition: Int): Int {
                return parentList[groupPosition].childItem.size
            }

            override fun getGroupCount(): Int {
                return parentList.size
            }

            override fun onCreateChildViewHolder(viewGroup: ViewGroup, viewType: Int): ViewHolder {
                val inflater = LayoutInflater.from(viewGroup.context)
                val binding = TpxakgBinding.inflate(inflater, viewGroup, false)
                return ChildViewHolder(binding)
            }

            override fun onCreateGroupViewHolder(viewGroup: ViewGroup, viewType: Int): ViewHolder {
                val inflater = LayoutInflater.from(viewGroup.context)
                val binding = MkisvqBinding.inflate(inflater, viewGroup, false)
                return ParentViewHolder(binding)
            }

            override fun onGroupViewHolderExpandChange(
                holder: ViewHolder, groupPosition: Int, animDuration: Long, expand: Boolean
            ) {

            }

            override fun onBindGroupViewHolder(
                holder: ViewHolder, groupPosition: Int, expand: Boolean, payloads: List<Any>
            ) {
                val viewHolder = holder as? ParentViewHolder ?: return
                val parentType = parentList[groupPosition]
                viewHolder.binding.pjvgubf.text = parentType.title
                parentType.expanded = expand
                if (parentType.expanded) {
                    viewHolder.binding.asycbam.setImageResource(R.mipmap.nhsllluj)
                } else {
                    viewHolder.binding.asycbam.setImageResource(R.mipmap.trqtrlre)
                }
                if (parentType.isfinish) {
                    viewHolder.binding.tubrjmb.isVisible = false
                    viewHolder.binding.kxxguwh.isVisible = true
                } else {
                    ValueAnimator.ofFloat(0f, 360f).run {
                        duration = 1000
                        repeatMode = ValueAnimator.RESTART
                        repeatCount = ValueAnimator.INFINITE
                        interpolator = LinearInterpolator()
                        addUpdateListener {
                            viewHolder.binding.tubrjmb.rotation = it.animatedValue as Float
                        }
                        start()
                    }
                    viewHolder.binding.tubrjmb.isVisible = true
                    viewHolder.binding.kxxguwh.isVisible = false
                }
                viewHolder.binding.qpeicyf.text = parentType.parentSize.toFormatSize(1)
                viewHolder.binding.asycbam.isVisible = parentType.childItem.isNotEmpty()
                viewHolder.binding.kxxguwh.isSelected = parentType.isParentSelected

                viewHolder.binding.kxxguwh.setTrackedOnClickListener {
                    viewHolder.binding.kxxguwh.isSelected = !viewHolder.binding.kxxguwh.isSelected
                    parentType.isParentSelected = !parentType.isParentSelected
                    if (parentType.isParentSelected) {
                        for (app in parentType.childItem) {
                            app.isChildSelected = true
                            notifyDataSetChanged()
                        }
                    } else {
                        for (app in parentType.childItem) {
                            app.isChildSelected = false
                            notifyDataSetChanged()
                        }
                    }
                    updateView()
                }
            }

            override fun onBindChildViewHolder(
                holder: ViewHolder, groupPosition: Int, childPosition: Int, payloads: List<Any>
            ) {
                val viewHolder = holder as? ChildViewHolder ?: return
                val childType = parentList[groupPosition].childItem[childPosition]
                when (groupPosition) {
                    0 -> {
                        val packageManager: PackageManager = this@Bihk.packageManager
                        val apkFilePath = childType.chilepath
                        val packageInfo = packageManager.getPackageArchiveInfo(
                                apkFilePath, PackageManager.GET_ACTIVITIES
                            )
                        if (packageInfo != null) {
                            val applicationInfo = packageInfo.applicationInfo
                            val appIcon = packageManager.getApplicationIcon(applicationInfo)
                            viewHolder.binding.xpeuctg.setImageDrawable(appIcon)
                        }
                    }

                    1 -> {
                        viewHolder.binding.xpeuctg.setImageResource(R.mipmap.otwyferi)
                    }

                    2 -> {
                        viewHolder.binding.xpeuctg.setImageResource(R.mipmap.npkjnxkh)
                    }

                    3 -> {

                    }

                    4 -> {

                    }
                }

                viewHolder.binding.henjylw.text = childType.childname
                viewHolder.binding.rsvaqrt.isSelected = childType.isChildSelected
                viewHolder.binding.yqtxlbe.text = childType.childSize.toFormatSize()
                viewHolder.itemView.setTrackedOnClickListener {
                    when (childPosition) {
                        childPosition -> {
                            viewHolder.binding.rsvaqrt.isSelected = !viewHolder.binding.rsvaqrt.isSelected
                            childType.isChildSelected = !childType.isChildSelected
                            if (!childType.isChildSelected) {
                                parentList[groupPosition].isParentSelected = false
                                notifyDataSetChanged()
                            }
                            updateView()
                        }
                    }
                }
            }

        }

    }

    private val child5 = ArrayList<ChildBean>()

    private val child4 = ArrayList<ChildBean>()

    private val child3 = ArrayList<ChildBean>()

    private val child2 = ArrayList<ChildBean>()

    override val isLightMode = false

    private fun addData(index: Int) {
        if (parentList.isNotEmpty()) {
            parentList[index].isfinish = true
            parentList[index].parentSize = sizes[index]
            mAdapter.notifyDataSetChanged()
        }
    }

    private fun setAdapter() {
        binding.cvyagwq.adapter = mAdapter
        binding.cvyagwq.layoutManager = LinearLayoutManager(this)
        scanJunk()
    }

    private fun scanJunk() {
        Oejm.getFileList({

        }, {
            Oejm.fileList.toList().let { it ->
                if (it.isNotEmpty()) {

                    val a = it.filter { it.isApk() }
                    val halfSize = if (a.size % 2 == 1) a.size / 2 + 1 else a.size / 2
                    val firstHalf = a.subList(0, halfSize)
                    a.forEach { l ->
                        sizes[0] += l.size
                        val bean = ChildBean(R.mipmap.wfxsvazf, l.name, l.path, l.size)
                        child3.add(bean)
                    }
                    ScanCount += 1
                    updateSize(doneIndex = 0)
                    val b = it.filter { it.isJunk() }
                    val bHalfSize = if (b.size % 2 == 1) b.size / 2 + 1 else b.size / 2
                    val bFirstHalf = b.subList(0, bHalfSize)
                    b.forEach { l ->
                        sizes[1] += l.size
                        val bean = ChildBean(null, l.name, l.path, l.size)
                        child4.add(bean)
                    }
                    ScanCount += 1
                    updateSize(doneIndex = 1)
                    val c = it.filter { it.isOtherTrash() }
                    val cHalfSize = if (c.size % 2 == 1) c.size / 2 + 1 else c.size / 2
                    val cFirstHalf = c.subList(0, cHalfSize)
                    c.forEach { l ->
                        sizes[2] += l.size
                        val bean = ChildBean(null, l.name, l.path, l.size)
                        child5.add(bean)
                    }
                    ScanCount += 2
                    updateSize(doneIndex = 2)
                }
            }
        })
    }

    override fun initView() {
        BarUtils.setStatusBarColor(this, Color.TRANSPARENT)
        binding.root.updatePadding(top = BarUtils.getStatusBarHeight())
        setAdapter()
        binding.lauoegi.setTrackedOnClickListener {
            onBackPressedDispatcher.onBackPressed()
        }
        onBackPressedDispatcher.addCallback(object : OnBackPressedCallback(true) {
            override fun handleOnBackPressed() {
                Utdc.showInterstitialAd(this@Bihk) {
                    finishToMain()
                }
            }

        })
        binding.muthfcv.setTrackedOnClickListener {
            startActivity(
                Intent(this, Svyw::class.java)
                    .putExtra(R.string.ފޗތށޞ_D.string(), selectList.toTypedArray())
                    .putExtra(R.string.ޜޑސއޗ_D.string(), selectSize)
            )
            finish()
        }
    }

    private fun updateView() {
        selectList.clear()
        var allSize = 0L
        for (i in parentList.indices) {
            if (parentList[i].childItem.isNotEmpty()) {
                val childSize = parentList[i].childItem.filter {
                    it.isChildSelected
                }.sumOf {
                    it.childSize
                }
                for (a in parentList[i].childItem) {
                    if (a.isChildSelected) {
                        if (a.pathList?.isNotEmpty() == true) {
                            for (o in a.pathList!!) {
                                selectList.add(o)
                            }
                        }
                    }
                }
                allSize += childSize
            } else {
                if (parentList[i].isParentSelected) {
                    allSize += parentList[i].parentSize
                }
            }

        }
        selectSize = allSize
        binding.muthfcv.text = R.string.ށޖބގށ_D.string((allSize.toFormatSize()).toString())
        binding.muthfcv.isEnabled = allSize > 0
        parentList.forEach { parent ->
            selectList.addAll(parent.childItem.filter {
                it.isChildSelected
            }.map { it.chilepath })
        }
    }

    private fun updateSize(doneIndex: Int = -1) {

        addData(index = doneIndex)
        val split = sizes.sum().toFormatSize(1).split(' ')
        binding.raputrh.text = split[0]
        binding.rowpmim.text = split[1]
        if (ScanCount >= 3) {
            selectList.clear()
            selectSize = 0L
            for (i in parentList.indices) {
                if (parentList[i].childItem.isNotEmpty()) {
                    val childSize = parentList[i].childItem.filter {
                        it.isChildSelected
                    }.sumOf {
                        it.childSize
                    }
                    for (a in parentList[i].childItem) {
                        if (a.isChildSelected) {
                            if (a.pathList?.isNotEmpty() == true) {
                                for (o in a.pathList!!) {
                                    selectList.add(o)
                                }
                            }
                        }
                    }
                    selectSize += childSize
                } else {
                    if (parentList[i].isParentSelected) {
                        selectSize += parentList[i].parentSize
                    }
                }

            }
            parentList.forEach { parent ->
                selectList.addAll(parent.childItem.filter {
                    it.isChildSelected
                }.map { it.chilepath })
            }
        }
        binding.muthfcv.isVisible = ScanCount >= 3
        binding.muthfcv.isEnabled = sizes.sum() > 0
        if (ScanCount >= 3 && sizes.sum().toInt() == 0) {
            Utdc.showInterstitialAd(this) {
                startActivity(
                    Intent(this, Iqnb::class.java).putExtra(
                        R.string.ޣޟމޅކ_D.string(), Dsce.JUNK_CLEANER
                    ).putExtra(R.string.ޠޜޚސޙ_D.string(), 0L)
                )
                finish()
            }
        }
        binding.muthfcv.text = R.string.ށޖބގށ_D.string((selectSize.toFormatSize(1)).toString())
    }
}