package rowedto.jockeyedto.sheetedto.atticedto.directionedto.noxiousedto.batedto

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.AheadedtoBinding
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import rowedto.jockeyedto.sheetedto.atticedto.Softedto
import rowedto.jockeyedto.sheetedto.atticedto.expandedto.colonyedto.dietedto.Successedto
import rowedto.jockeyedto.sheetedto.balsamedto.formaledto.orientationedto.Patedto.showExitFunctionDialog
import rowedto.jockeyedto.sheetedto.balsamedto.formaledto.orientationedto.Patedto.showGerPermission
import rowedto.jockeyedto.sheetedto.debutedto.revolutionaryedto.ChildBean
import rowedto.jockeyedto.sheetedto.debutedto.revolutionaryedto.Dynamicedto.JUNK_CLEANER
import rowedto.jockeyedto.sheetedto.knewedto.economicedto.copyrightedto.Crossingedto
import rowedto.jockeyedto.sheetedto.knewedto.economicedto.copyrightedto.Studiededto.checkStorePermission
import rowedto.jockeyedto.sheetedto.knewedto.economicedto.copyrightedto.Studiededto.requestStorePermission
import rowedto.jockeyedto.sheetedto.knewedto.economicedto.copyrightedto.Suitcaseedto.toFormatSize
import rowedto.jockeyedto.sheetedto.meadowedto.naturaledto.idealedto.Choseedto
import rowedto.jockeyedto.sheetedto.raceedto.pavementedto.Responsibilityedto
import rowedto.jockeyedto.sheetedto.raceedto.pavementedto.Spareedto
import rowedto.jockeyedto.sheetedto.raceedto.pavementedto.Stewardedto
import rowedto.jockeyedto.sheetedto.strangeedto.pyramidedto.particlesedto.Scandaledto
import java.io.File
import kotlin.random.Random

/**
 * 清理数据获取页面
 */
class Childishedto : Crossingedto<AheadedtoBinding>() {

    private val TAG = "CleanJunkActivity"

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

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

        junkExpandAdapter = Choseedto { size ->
            if (size == 0L) {
                binding.recordingedto.text = "Got it"
                binding.bulletinedto.text = "0"
                binding.figureedto.text = "B"
            } else {
                binding.recordingedto.text = "Clean up ${size.toFormatSize(1)}"
                val split = size.toFormatSize().split(" ")
                binding.bulletinedto.text = split[0]
                binding.figureedto.text = split[1]
            }
            if (scanFinish) {
                if (junkExpandAdapter.getAllChildItemCount() == 0) {
                    binding.recordingedto.visibility = View.VISIBLE
                    binding.recordingedto.isEnabled = true
                    binding.rentedto.visibility = View.GONE
                } else {
                    binding.recordingedto.isVisible = true
                    binding.recordingedto.isEnabled = true
                }
            }
        }
        binding.sliceedto.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.conditionedto.setOnClickListener {
            onBackPressedDispatcher.onBackPressed()
        }
        onBackPressedDispatcher.addCallback(object : OnBackPressedCallback(true) {
            override fun handleOnBackPressed() {
                showExitFunctionDialog {
                    if (it) {
                        Scandaledto.admobMaxShowInterstitialAd(this@Childishedto, false) {
                            finishToMain()
                        }
                    } else {
                        finishToMain()
                    }
                }
            }

        })
        binding.recordingedto.setOnClickListener {

            when (binding.recordingedto.text) {
                "Got it" -> {
                    val showJunkBtnAd = Stewardedto.getInstance().getString("isGotItplayAd", "0").toInt()
                    if (showJunkBtnAd == 1) {
                        Scandaledto.admobMaxShowInterstitialAd(this) {
                            startActivity(Intent(this@Childishedto, Softedto::class.java).apply {
                                putExtra("clean_size", JUNK_CLEANER)
                                putExtra("from", 0)
                            })
                            finish()
                        }
                    } else {
                        startActivity(Intent(this@Childishedto, Softedto::class.java).apply {
                            putExtra("clean_size", JUNK_CLEANER)
                            putExtra("from", 0)
                        })
                        finish()
                    }

                }

                else -> {
                    val showJunkBtnAd = Stewardedto.getInstance().getString("isGotItplayAd", "0").toInt()
                    if (showJunkBtnAd == 1) {
                        Scandaledto.admobMaxShowInterstitialAd(this) {
                            startActivity(
                                Intent(this, Negativeedto::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()
                        }
                    } else {
                        startActivity(
                            Intent(this, Negativeedto::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()
                    }
                }
            }

        }

        binding.mouthedto.setOnClickListener {
            val showJunkBtnAd = Stewardedto.getInstance().getString("isGotItplayAd", "0").toInt()
            if (showJunkBtnAd == 1) {
                Scandaledto.admobMaxShowInterstitialAd(this) {
                    startActivity(Intent(this@Childishedto, Softedto::class.java).apply {
                        putExtra("clean_size", JUNK_CLEANER)
                        putExtra("from", 0)
                    })
                    finish()
                }
            } else {
                startActivity(Intent(this@Childishedto, Softedto::class.java).apply {
                    putExtra("clean_size", JUNK_CLEANER)
                    putExtra("from", 0)
                })
                finish()
            }

        }
        binding.spectrumedto.setOnClickListener {
            startActivity(Intent(this, Successedto::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.layersedto, l.name, l.path, l.length()))
            }
            delay(Random.nextLong(1500, 2000))
        }.await()
//        async {
//            val emptyFolder1 = Everythingedto.getFileFolder(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM))
//            val emptyFolder2 = Everythingedto.getFileFolder(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS))
//            val emptyFolder3 = Everythingedto.getFileFolder(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS))
//            val emptyFolder4 = Everythingedto.getFileFolder(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES))
//            val emptyFolder5 = Everythingedto.getFileFolder(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES))
//            val emptyFolder6 = Everythingedto.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.layersedto, l.name, l.path, 1))
//            }
//            delay(Random.nextLong(1500, 2000))
//        }.await()
        junkExpandAdapter.addChildData(0, list)


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


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

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