package importantedto.appliededto.surgeonedto.promiseedto.prospectedto.consumptionedto.blameedto

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Color
import android.os.Environment
import android.view.View
import androidx.activity.OnBackPressedCallback
import androidx.core.view.isVisible
import androidx.lifecycle.lifecycleScope
import com.base.datarecovery.R
import com.base.datarecovery.databinding.CaneedtoBinding
import importantedto.admireedto.sweptedto.Differenceedto
import importantedto.afteredto.constitutionaledto.Constraintedto.toFormatSize
import importantedto.afteredto.constitutionaledto.Murderedto
import importantedto.afteredto.constitutionaledto.Rackedto.checkStorePermission
import importantedto.afteredto.constitutionaledto.Rackedto.requestStorePermission
import importantedto.appliededto.surgeonedto.promiseedto.Halcyonedto
import importantedto.appliededto.surgeonedto.promiseedto.produceredto.motionedto.momentumedto.Collectionedto
import importantedto.concreteedto.cameedto.ChildBean
import importantedto.concreteedto.cameedto.Hateedto.JUNK_CLEANER
import importantedto.deserveedto.manufactureredto.viableedto.Wayedto
import importantedto.gallonedto.Transcendedto
import importantedto.gallonedto.Waitedto
import importantedto.gallonedto.Youthedto
import importantedto.maidedto.witnessedto.nationalismedto.Photocopyedto.showExitFunctionDialog
import importantedto.maidedto.witnessedto.nationalismedto.Photocopyedto.showGerPermission
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.io.File
import kotlin.random.Random

/**
 * 清理数据获取页面
 */
class Amberedto : Murderedto<CaneedtoBinding>() {

    private val TAG = "CleanJunkActivity"

    override val binding: CaneedtoBinding by lazy {
        CaneedtoBinding.inflate(layoutInflater)
    }
    private lateinit var junkExpandAdapter: Wayedto

    @SuppressLint("SetTextI18n", "NotifyDataSetChanged")
    override fun initView() {
        Transcendedto.setStatusBarLightMode(this, true)
        Transcendedto.setStatusBarColor(this, Color.TRANSPARENT)
//        binding.root.updatePadding(top = Transcendedto.getStatusBarHeight())

        junkExpandAdapter = Wayedto { size ->
            if (size == 0L) {
                binding.trolleyedto.text = "Got it"
                binding.ignoranceedto.text = "0"
                binding.cheatedto.text = "B"
            } else {
                binding.trolleyedto.text = "Clean up ${size.toFormatSize(1)}"
                val split = size.toFormatSize().split(" ")
                binding.ignoranceedto.text = split[0]
                binding.cheatedto.text = split[1]
            }
            if (scanFinish) {
                if (junkExpandAdapter.getAllChildItemCount() == 0) {
                    binding.trolleyedto.visibility = View.VISIBLE
                    binding.trolleyedto.isEnabled = true
                    binding.princeedto.visibility = View.GONE
                } else {
                    binding.trolleyedto.isVisible = true
                    binding.trolleyedto.isEnabled = true
                }
            }
        }
        binding.roomedto.adapter = junkExpandAdapter


        if (checkStorePermission()) {
            scanJunk()
        } else {
            showGerPermission(
                desc = "This feature requires access to your storage to scan your files and clean up junk files and unused APK files. We will not transmit your data to any third-party service. Please grant permission so that we can provide you with better service.",
                deny = { finishToMain() }, allow = {
                    requestStorePermission(launcher) {
                        scanJunk()
                    }
                })
        }
    }

    override fun initListener() {
        binding.bangedto.setOnClickListener {
            onBackPressedDispatcher.onBackPressed()
        }
        onBackPressedDispatcher.addCallback(object : OnBackPressedCallback(true) {
            override fun handleOnBackPressed() {
                showExitFunctionDialog {
                    if (it) {
                        Differenceedto.admobMaxShowInterstitialAd(this@Amberedto, false) {
                            finishToMain()
                        }
                    } else {
                        finishToMain()
                    }
                }
            }

        })
        binding.trolleyedto.setOnClickListener {

            when (binding.trolleyedto.text) {
                "Got it" -> {
                    val showJunkBtnAd = Waitedto.getInstance().getString("isGotItplayAd", "0").toInt()
                    if (showJunkBtnAd == 1) {
                        Differenceedto.admobMaxShowInterstitialAd(this) {
                            startActivity(Intent(this@Amberedto, Halcyonedto::class.java).apply {
                                putExtra("clean_size", JUNK_CLEANER)
                                putExtra("from", 0)
                            })
                            finish()
                        }
                    } else {
                        startActivity(Intent(this@Amberedto, Halcyonedto::class.java).apply {
                            putExtra("clean_size", JUNK_CLEANER)
                            putExtra("from", 0)
                        })
                        finish()
                    }

                }

                else -> {
                    val showJunkBtnAd = Waitedto.getInstance().getString("isGotItplayAd", "0").toInt()
                    if (showJunkBtnAd == 1) {
                        Differenceedto.admobMaxShowInterstitialAd(this) {
                            startActivity(
                                Intent(this, Confusionedto::class.java).apply {
                                    val list = junkExpandAdapter.getChoosePath()
                                    putExtra("list", list.map { it.chilepath }.toTypedArray())
                                    putExtra("size", list.sumOf { it.childSize })
                                }
                            )
                            finish()
                        }
                    } else {
                        startActivity(
                            Intent(this, Confusionedto::class.java).apply {
                                val list = junkExpandAdapter.getChoosePath()
                                putExtra("list", list.map { it.chilepath }.toTypedArray())
                                putExtra("size", list.sumOf { it.childSize })
                            }
                        )
                        finish()
                    }
                }
            }

        }

        binding.explainedto.setOnClickListener {
            val showJunkBtnAd = Waitedto.getInstance().getString("isGotItplayAd", "0").toInt()
            if (showJunkBtnAd == 1) {
                Differenceedto.admobMaxShowInterstitialAd(this) {
                    startActivity(Intent(this@Amberedto, Halcyonedto::class.java).apply {
                        putExtra("clean_size", JUNK_CLEANER)
                        putExtra("from", 0)
                    })
                    finish()
                }
            } else {
                startActivity(Intent(this@Amberedto, Halcyonedto::class.java).apply {
                    putExtra("clean_size", JUNK_CLEANER)
                    putExtra("from", 0)
                })
                finish()
            }

        }
        binding.yinedto.setOnClickListener {
            startActivity(Intent(this, Collectionedto::class.java).apply {
                putExtra("tittle", "Deep Scan")
            })
            finish()
        }

    }

    var scanFinish: Boolean = false
    private fun scanJunk() = lifecycleScope.launch(Dispatchers.Main) {

        var totalSize = 0L

        val list = arrayListOf<ChildBean>()
        async {
            val empty = findEmptyFolders()
            empty.filter { it.listFiles().isNullOrEmpty() }.forEach { l ->
                totalSize += l.length()
                list.add(ChildBean(R.mipmap.ventureedto, l.name, l.path, l.length()))
            }
            delay(Random.nextLong(1500, 2000))
        }.await()
//        async {
//            val emptyFolder1 = Concessionedto.getFileFolder(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM))
//            val emptyFolder2 = Concessionedto.getFileFolder(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS))
//            val emptyFolder3 = Concessionedto.getFileFolder(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS))
//            val emptyFolder4 = Concessionedto.getFileFolder(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES))
//            val emptyFolder5 = Concessionedto.getFileFolder(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES))
//            val emptyFolder6 = Concessionedto.getFileFolder(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC))
//            val emptyFolder = arrayListOf<File>()
//            emptyFolder.addAll(emptyFolder1)
//            emptyFolder.addAll(emptyFolder2)
//            emptyFolder.addAll(emptyFolder3)
//            emptyFolder.addAll(emptyFolder4)
//            emptyFolder.addAll(emptyFolder5)
//            emptyFolder.addAll(emptyFolder6)
//            emptyFolder.filter { it.listFiles().isNullOrEmpty() }.forEach { l ->
//                list.add(ChildBean(R.mipmap.ventureedto, l.name, l.path, 1))
//            }
//            delay(Random.nextLong(1500, 2000))
//        }.await()
        junkExpandAdapter.addChildData(0, list)


        list.clear()
        async {
            val apk = Youthedto.queryFiles(this@Amberedto, Youthedto.FileType.APK) ?: listOf()
            apk.forEach { l ->
                totalSize += l.size
                list.add(ChildBean(R.mipmap.linearedto, l.name, l.path, l.size))
            }
//            if (BuildConfig.DEBUG) {
//                repeat(5) {
//                    val size = Random.nextLong(500)
//                    totalSize += size
//                    list.add(ChildBean(R.mipmap.linearedto, "1", "apl$it", size))
//                }
//            }
            delay(Random.nextLong(1500, 2000))
        }.await()
        junkExpandAdapter.addChildData(1, list)


        list.clear()
        async {
            val temp = Youthedto.queryFiles(this@Amberedto, Youthedto.FileType.TMP) ?: listOf()
            temp.forEach { l ->
                totalSize += l.size
                list.add(ChildBean(R.mipmap.rootedto, l.name, l.path, l.size))
            }
//            if (BuildConfig.DEBUG) {
//                repeat(5) {
//                    val size = Random.nextLong(500)
//                    totalSize += size
//                    list.add(ChildBean(R.mipmap.rootedto, "1", "temp$it", size))
//                }
//            }
            delay(Random.nextLong(1500, 2000))
        }.await()
        junkExpandAdapter.addChildData(2, list)

        list.clear()
        async {
            val log = Youthedto.queryFiles(this@Amberedto, Youthedto.FileType.LOG) ?: listOf()
            log.forEach { l ->
                totalSize += l.size
                list.add(ChildBean(R.mipmap.strapedto, l.name, l.path, l.size))
            }
//            if (BuildConfig.DEBUG) {
//                repeat(5) {
//                    val size = Random.nextLong(500)
//                    totalSize += size
//                    list.add(ChildBean(R.mipmap.strapedto, "1", "log$it", size))
//                }
//            }
            delay(Random.nextLong(1500, 2000))
        }.await()

        scanFinish = true
        junkExpandAdapter.addChildData(3, list)


    }


    override fun onDestroy() {
        super.onDestroy()
        junkExpandAdapter.animators.values.forEach {
            it.cancel()
        }
    }
    fun findEmptyFolders(): List<File> {
        val externalStorageDir = Environment.getExternalStorageDirectory()
        val filters = arrayOf("/storage/emulated/0/Android/data", "/storage/emulated/0/Android/obb")
        val emptyFolders = getAllEmptyFolders(externalStorageDir, filters)
        return emptyFolders
    }
    private fun getAllEmptyFolders(root: File, filters: Array<String>): List<File> {
        return root.walk()
            .filter {
                it.isDirectory && !filters.contains(it.path) && !it.isHidden && it.list()
                    ?.isEmpty() == true
            }
            .toList()
    }
}