package rallyedto.finishedto.hypothesisedto.vegetableedto.breakfastedto

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Color
import android.os.Environment
import android.view.View
import androidx.activity.addCallback
import androidx.core.view.isVisible
import androidx.core.view.updatePadding
import androidx.lifecycle.lifecycleScope
import com.base.datarecovery.R
import com.base.datarecovery.databinding.DeteriorateedtoBinding
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import rallyedto.battleedto.acresedto.Fireplaceedto.toFormatSize
import rallyedto.battleedto.acresedto.Lemonedto
import rallyedto.battleedto.acresedto.Napedto.checkStorePermission
import rallyedto.battleedto.acresedto.Napedto.requestStorePermission
import rallyedto.dumpedto.editionedto.Eagleedto
import rallyedto.farewelledto.Technologyedto.showExitFunctionDialog
import rallyedto.farewelledto.Technologyedto.showGerPermission
import rallyedto.finishedto.Screamedto
import rallyedto.policeedto.huntedto.ChildBean
import rallyedto.policeedto.huntedto.Snuggleedto.JUNK_CLEANER
import rallyedto.sunedto.tumouredto.majorityedto.loseedto.Togetheredto
import rallyedto.talledto.blewedto.Islandedto
import rallyedto.talledto.blewedto.Localedto
import java.io.File
import kotlin.random.Random

/**
 * 清理数据获取页面
 */
class Describeedto : Lemonedto<DeteriorateedtoBinding>() {

    private val TAG = "CleanJunkActivity"

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

    @SuppressLint("SetTextI18n", "NotifyDataSetChanged")
    override fun initView() {
        Islandedto.setStatusBarLightMode(this, true)
        Islandedto.setStatusBarColor(this, Color.TRANSPARENT)
        binding.roaredto.updatePadding(top = Islandedto.getStatusBarHeight())
        Togetheredto.showNativeAd(this, binding.jeweledto)
        junkExpandAdapter = Eagleedto { size ->
            if (size == 0L) {
                binding.franchiseedto.text = "Go it"
                binding.startedto.text = "0"
                binding.becomeedto.text = "B"
            } else {
                binding.franchiseedto.text = "Clean up ${size.toFormatSize(1)}"
                val split = size.toFormatSize().split(" ")
                binding.startedto.text = split[0]
                binding.becomeedto.text = split[1]
            }
            if (scanFinish) {
                if (junkExpandAdapter.getAllChildItemCount() == 0) {
                    binding.franchiseedto.visibility = View.VISIBLE
                    binding.franchiseedto.isEnabled = true
                } else {
                    binding.franchiseedto.isVisible = true
                    binding.franchiseedto.isEnabled = true
                }
            }
        }
        binding.willpoweredto.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.unfortunateedto.setOnClickListener {
            onBackPressedDispatcher.onBackPressed()
        }
        onBackPressedDispatcher.addCallback {
            showExitFunctionDialog {
                admobMaxShowInterstitialAd(isShow = Togetheredto.isShowAdBackInter()) {
                    finishToMain()
                }
            }
        }

        binding.franchiseedto.setOnClickListener {

            when (binding.franchiseedto.text) {
                "Go it" -> {
                    admobMaxShowInterstitialAd(true) {
                        startActivity(
                            Intent(
                                this@Describeedto,
                                Screamedto::class.java
                            ).apply {
                                putExtra("clean_size", JUNK_CLEANER)
                                putExtra("from", 0)
                            })
                        finish()
                    }
                }

                else -> {
                    admobMaxShowInterstitialAd(true) {
                        startActivity(
                            Intent(this, Drugedto::class.java).apply {
                                val list = junkExpandAdapter.getChoosePath()
                                putExtra("type", JUNK_CLEANER)
                                putExtra("list", list.map { it.chilepath }.toTypedArray())
                                putExtra("size", list.sumOf { it.childSize })
                            }
                        )
                        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.essayedto, l.name, l.path, l.length()))
            }
            delay(Random.nextLong(1500, 2000))
        }.await()
//        async {
//            val emptyFolder1 = Circulationedto.getFileFolder(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM))
//            val emptyFolder2 = Circulationedto.getFileFolder(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS))
//            val emptyFolder3 = Circulationedto.getFileFolder(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS))
//            val emptyFolder4 = Circulationedto.getFileFolder(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES))
//            val emptyFolder5 = Circulationedto.getFileFolder(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES))
//            val emptyFolder6 = Circulationedto.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.essayedto, l.name, l.path, 1))
//            }
//            delay(Random.nextLong(1500, 2000))
//        }.await()
        junkExpandAdapter.addChildData(0, list)


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


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

        list.clear()
        async {
            val log =
                Localedto.queryFiles(this@Describeedto, Localedto.FileType.LOG)
                    ?: listOf()
            log.forEach { l ->
                totalSize += l.size
                list.add(ChildBean(R.mipmap.unicornedto, l.name, l.path, l.size))
            }
//            if (BuildConfig.DEBUG) {
//                repeat(5) {
//                    val size = Random.nextLong(500)
//                    totalSize += size
//                    list.add(ChildBean(R.mipmap.unicornedto, "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()
    }
}