package com.zxhyis.toolss.ui.page

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Color
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.cleanmaster.junk.bean.SDcardRubbishResult
import com.cloud.cleanjunksdk.ad.AdvBean
import com.cloud.cleanjunksdk.cache.CacheBean
import com.cloud.cleanjunksdk.filescan.ApkBean
import com.cloud.cleanjunksdk.filescan.LogBean
import com.cloud.cleanjunksdk.filescan.TmpBean
import com.cloud.cleanjunksdk.residual.ResidualBean
import com.cloud.cleanjunksdk.task.CheckSdkCallback
import com.cloud.cleanjunksdk.task.Clean
import com.cloud.cleanjunksdk.task.CleanSDK
import com.cloud.cleanjunksdk.task.JunkScanCallback
import com.cloud.cleanjunksdk.tools.Region
import com.cm.plugincluster.junkengine.junk.bean.MediaFile
import com.cm.plugincluster.junkengine.junk.engine.MEDIA_TYPE
import com.zxhyis.toolss.FileApp
import com.zxhyis.toolss.R
import com.zxhyis.toolss.ad.AdmobUtils
import com.zxhyis.toolss.base.TopActivity
import com.zxhyis.toolss.cx.FileHelps.toFormatSize
import com.zxhyis.toolss.databinding.ActivityLayoutJunksBinding
import com.zxhyis.toolss.logic.ChildBean
import com.zxhyis.toolss.logic.Logic
import com.zxhyis.toolss.logic.ParentBean
import com.zxhyis.toolss.logic.setOnClick
import com.zxhyis.toolss.ui.AFunOb
import com.zxhyis.toolss.ui.adapter.JunkAdapter
import com.zxhyis.toolss.ui.page.result.ResultActivity

class JunksActivity : TopActivity<ActivityLayoutJunksBinding>() {
    // private val parentList = mutableListOf<ParentBean>()
    private val parentList = ArrayList<ParentBean>()
    private val child1 = ArrayList<ChildBean>()
    private val child2 = ArrayList<ChildBean>()
    private val child3 = ArrayList<ChildBean>()
    private val child4 = ArrayList<ChildBean>()
    private val child5 = ArrayList<ChildBean>()
    private val sizes = MutableList(5) { 0L }
    private lateinit var cleanAdapter: JunkAdapter
    private var ScanCount = 0
    private val selectList = mutableListOf<String>()
    private val adPathlist = mutableListOf<String>()
    private var selectSize = 0L

    //    private var CurrentChoose
    override fun getViewBinding1(): ActivityLayoutJunksBinding {
        return ActivityLayoutJunksBinding.inflate(layoutInflater)
    }

    private var sdkClean: Clean? = null

    override fun init() {
        BarUtils.setStatusBarLightMode(this, true)
        BarUtils.setStatusBarColor(this, Color.TRANSPARENT)
        vb.root.updatePadding(top = BarUtils.getStatusBarHeight())
        initAdapter()
        vb.idJunksBack.setOnClick(javaClass.simpleName) {
            onBackPressedDispatcher.onBackPressed()
        }
        onBackPressedDispatcher.addCallback(object : OnBackPressedCallback(true) {
            override fun handleOnBackPressed() {
                AdmobUtils.showInterstitialAd(this@JunksActivity) {
                    finishToMain()
                }

            }

        })
        vb.idClBtn.setOnClick(javaClass.simpleName) {
            startActivity(
                Intent(this, CleaningActivity::class.java)
                    .putExtra("list", selectList.toTypedArray())
                    // .putExtra("path", selectList.)
                    .putExtra("size", selectSize)
            )
            finish()
        }
    }


    private fun initSdk() {
        CleanSDK.init(FileApp.fContext, FileApp.fContext, Region.INTL, object : CheckSdkCallback {
            override fun onSuccess(p0: Clean?) {
                sdkClean = p0
                startScan()
                //Log.e("MXL", "onSuccess: ")
            }

            override fun onError(p0: Int) {
               // Log.e("MXL", "onError: " + p0)
            }

        })

    }

    private fun addData(index: Int) {
        if (parentList.isNotEmpty()) {
            parentList[index].isfinish = true
            parentList[index].parentSize = sizes[index]
            cleanAdapter.UpdateData()
            // junkList = parentList.toMutableList()
            //   Log.e("MXL", "addData: " + junkList.size + "Data:" + junkList.toString())
        }
//        when (index) {
//            0 -> {
//                parentList.add(
//                    ParentBean
//                        (
//                        title = "Cache garbage",
//                        childItem = child1,
//                        parentSize = sizes[index],
//                        isParentSelected = true,
//                        expanded = false
//                    )
//                )
//            }
//
//            1 -> {
//                parentList.add(
//                    ParentBean
//                        (
//                        title = "Advertising waste",
//                        childItem = child2,
//                        parentSize = sizes[index],
//                        isParentSelected = true,
//                        expanded = false
//                    )
//                )
//            }
//
//            2 -> {
//                parentList.add(
//                    ParentBean
//                        (
//                        title = "Useless installation package",
//                        childItem = child3,
//                        parentSize = sizes[index],
//                        isParentSelected = true,
//                        expanded = false
//                    )
//                )
//            }
//
//            3 -> {
//                parentList.add(
//                    ParentBean
//                        (
//                        title = "Residual junk files",
//                        childItem = child4,
//                        parentSize = sizes[index],
//                        isParentSelected = true,
//                        expanded = false
//                    )
//                )
//            }
//
//            4 -> {
//                parentList.add(
//                    ParentBean
//                        (
//                        title = "Clean up more",
//                        childItem = child5,
//                        parentSize = sizes[index],
//                        isParentSelected = true,
//                        expanded = false
//                    )
//                )
//            }
//        }
    }

    private fun initAdapter() {
        parentList.apply {
            parentList.add(
                ParentBean
                    (
                    title = "Cache Junk",
                    childItem = child1,
                    parentSize = sizes[0],
                    isParentSelected = true,
                    expanded = false
                )
            )
            parentList.add(
                ParentBean
                    (
                    title = "Advertising waste",
                    childItem = child2,
                    parentSize = sizes[1],
                    isParentSelected = true,
                    expanded = false
                )
            )
            parentList.add(
                ParentBean
                    (
                    title = "Useless installation package",
                    childItem = child3,
                    parentSize = sizes[2],
                    isParentSelected = true,
                    expanded = false
                )
            )
            parentList.add(
                ParentBean
                    (
                    title = "Residual junk files",
                    childItem = child4,
                    parentSize = sizes[3],
                    isParentSelected = true,
                    expanded = false
                )
            )
            parentList.add(
                ParentBean
                    (
                    title = "Clean up more",
                    childItem = child5,
                    parentSize = sizes[4],
                    isParentSelected = true,
                    expanded = false
                )
            )

        }
        cleanAdapter = JunkAdapter(parentList, this, object : Logic {
            override fun doLogic() {
                // updateSize()
               // Log.e("MXL", "更新回调 ")
                updateView()
            }
        })
        vb.idExRl.adapter = cleanAdapter
        vb.idExRl.layoutManager = LinearLayoutManager(this)
        initSdk()
    }

    private fun startScan() {
        sdkClean?.startScan(object : JunkScanCallback {
            override fun onStart() {

            }

            override fun error(p0: Int, p1: Throwable?) {

            }

            override fun onCacheJunkEmitOne(p0: CacheBean?) {
               // Log.e("MXL", "应用缓存垃圾: " + p0)
                if (p0 != null) {
                    sizes[0] += p0.size
                    p0.pathBeen.forEach {
                        adPathlist.add(it.cleanPath)
                    }

                    val bean = ChildBean(null, p0.appName, "", p0.size, pathList = adPathlist)
                    child1.add(bean)
                }
            }

            override fun onCacheJunkSucceed() {
                ScanCount += 1
                updateSize(doneIndex = 0)
                //Log.e("MXL", "缓存垃圾扫描完成: ")
            }

            override fun onAdJunkEmitOne(p0: AdvBean?) {
                //广告垃圾
                if (p0 != null) {
                    sizes[1] += p0.size
                    //junkList.add(p0.path)
                    val bean = ChildBean(null, p0.name, p0.path, p0.size)
                    child2.add(bean)
                }

            }

            override fun onAdJunkSucceed() {
                ScanCount += 1
                updateSize(doneIndex = 1)
                //Log.e("MXL", "广告垃圾onAdJunkSucceed: " + "")
            }

            override fun onApkJunkEmitOne(p0: ApkBean?) {
                //无用安装包
                if (p0 != null) {
                    sizes[2] += p0.size
                    //  junkList.add(p0.path)
                    val bean = ChildBean(R.drawable.home_apk, p0.name, p0.path, p0.size)
                    child3.add(bean)
                }
            }

            override fun onApkJunkScanSucceed() {
                ScanCount += 1
                updateSize(doneIndex = 2)

                //Log.e("MXL", "onApkJunkScanSucceed: ")
            }


            override fun onLogJunkEmitOne(p0: LogBean?) {
                //log文件
            }

            override fun onLogJunkScanSucceed() {

            }


            override fun onResidualEmitOne(bean: ResidualBean?) {
                //卸载残留文件
                bean ?: return

                sizes[3] += JaHelp.getResiduaSize(bean)
                val bean = ChildBean(
                    null,
                    JaHelp.getResiduaDesc(bean),
                    JaHelp.getResiduaPath(bean),
                    JaHelp.getResiduaSize(bean)
                )
                child4.add(bean)
                // junkList.add(JaHelp.getResiduaPath(bean))

//                 sizes[3] = p0.size
//                 junkList.addAll(p0!!.path)

            }

            override fun onResidualJunkSucceed() {
                ScanCount += 1
                updateSize(doneIndex = 3)

               // Log.e("MXL", "onThumbnailJunkScanSucceed: ")
            }

            override fun onThumbnailJunkEmitOne(p0: SDcardRubbishResult?) {


            }

            override fun onThumbnailJunkScanSucceed() {

            }

            override fun onTmpJunkEmitOne(p0: TmpBean?) {
                //tmp文件
                if (p0 != null) {
                    sizes[4] += p0.size
                    //  junkList.add(p0.path)
                    val bean = ChildBean(null, p0.name, p0.path, p0.size)
                    child5.add(bean)
                }
            }

            override fun onTmpJunkScanSucceed() {
                ScanCount += 1
                updateSize(doneIndex = 4)
               // Log.e("MXL", "onTmpJunkScanSucceed: ")
            }

            override fun onMediaFileJunkEmitOne(p0: MEDIA_TYPE?, p1: MediaFile?) {

            }

            override fun onMediaFileJunkScanSucceed(p0: MEDIA_TYPE?) {

            }

            override fun onTimeOut() {

            }

        }, false)

    }

    private fun updateSize(doneIndex: Int = -1) {
        addData(index = doneIndex)
        val split = sizes.sum().toFormatSize(1).split(' ')
        vb.idKeCl.text = split[0]
        vb.idSizeUnit.text = split[1]
        if (ScanCount >= 5) {
            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 })
            }
        }

        vb.idClBtn.isVisible = ScanCount >= 5
        vb.idClBtn.isEnabled = sizes.sum() > 0
        if (ScanCount >= 5 && sizes.sum().toInt() == 0) {
            AdmobUtils.showInterstitialAd(this) {
                startActivity(
                    Intent(
                        this, ResultActivity::class.java
                    ).putExtra("from", AFunOb.JUNK_CLEANER)
                        .putExtra("clean_size", 0L)
                )
                // startActivity<ResultActivity>("from" to "clean", "clean_size" to x)
                finish()
            }
        }
        vb.idClBtn.text = "Clean up ${selectSize.toFormatSize(1)}"
    }


    @SuppressLint("SetTextI18n")
    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 {
//                val parentSelectSize = parentList.filter {
//                    it.isParentSelected
//                }.sumOf {
//                    it.parentSize
//                }
                if (parentList[i].isParentSelected) {
                    allSize += parentList[i].parentSize
                }
            }

        }
        selectSize = allSize
        vb.idClBtn.text = "Clean up ${allSize.toFormatSize()}"
        vb.idClBtn.isEnabled = allSize > 0
        parentList.forEach { parent ->
            selectList.addAll(parent.childItem.filter {
                it.isChildSelected
            }.map { it.chilepath })
        }

//        for (item in parentList) {
//            if (item.isParentSelected) {
//                Log.e("MXL", "updateView: " + item)
//            }
//        }

    }

}