package com.base.filerecoveryrecyclebin.activity.junkclean

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Color
import android.os.Environment
import androidx.activity.OnBackPressedCallback
import androidx.core.view.isVisible
import androidx.lifecycle.lifecycleScope
import com.base.filerecoveryrecyclebin.BuildConfig
import com.base.filerecoveryrecyclebin.R
import com.base.filerecoveryrecyclebin.activity.ResultActivity
import com.base.filerecoveryrecyclebin.activity.photomanager.PhotoManagerAnimationActivity
import com.base.filerecoveryrecyclebin.adapter.JunkExpandAdapter
import com.base.filerecoveryrecyclebin.ads.AdmobMaxHelper
import com.base.filerecoveryrecyclebin.bean.ChildBean
import com.base.filerecoveryrecyclebin.bean.ConstObject.JUNK_CLEANER
import com.base.filerecoveryrecyclebin.databinding.ActivityLayoutCleanJunkBinding
import com.base.filerecoveryrecyclebin.help.BaseActivity
import com.base.filerecoveryrecyclebin.help.FileHelp
import com.base.filerecoveryrecyclebin.help.KotlinExt.toFormatSize
import com.base.filerecoveryrecyclebin.help.PermissionHelp.checkStorePermission
import com.base.filerecoveryrecyclebin.help.PermissionHelp.requestStorePermission
import com.base.filerecoveryrecyclebin.utils.BarUtils
import com.base.filerecoveryrecyclebin.utils.MediaStoreUtils
import com.base.filerecoveryrecyclebin.view.DialogViews.showExitFunctionDialog
import com.base.filerecoveryrecyclebin.view.DialogViews.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 CleanJunkActivity : BaseActivity<ActivityLayoutCleanJunkBinding>() {

    private val TAG = "CleanJunkActivity"

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

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

        junkExpandAdapter = JunkExpandAdapter { size ->
            if (size == 0L) {
                binding.tvBtn.text = "Got it"
                binding.tvSize.text = "0"
                binding.tvUnit.text = "B"
            } else {
                binding.tvBtn.text = "Clean up ${size.toFormatSize(1)}"
                val split = size.toFormatSize().split(" ")
                binding.tvSize.text = split[0]
                binding.tvUnit.text = split[1]
            }
            if (junkExpandAdapter.getAllChildItemCount() == 0) {
                binding.tvBtn.text = "Deep Clean"
            }
        }
        binding.exRv.adapter = junkExpandAdapter


        if (checkStorePermission()) {
            scanJunk()
        } else {
            showGerPermission(desc = "", deny = { finishToMain() }, allow = {
                requestStorePermission(launcher) {
                    scanJunk()
                }
            })
        }
    }

    override fun initListener() {
        binding.flFanhui.setOnClickListener {
            onBackPressedDispatcher.onBackPressed()
        }
        onBackPressedDispatcher.addCallback(object : OnBackPressedCallback(true) {
            override fun handleOnBackPressed() {
                showExitFunctionDialog {
                    if (it) {
                        AdmobMaxHelper.admobMaxShowInterstitialAd(this@CleanJunkActivity) {
                            finishToMain()
                        }
                    } else {
                        finishToMain()
                    }
                }
            }

        })
        binding.tvBtn.setOnClickListener {

            when (binding.tvBtn.text) {
                "Got it" -> {
                    startActivity(Intent(this@CleanJunkActivity, ResultActivity::class.java).apply {
                        putExtra("clean_size", JUNK_CLEANER)
                        putExtra("from", 0)
                    })
                }

                "Deep Clean" -> {
                    startActivity(Intent(this@CleanJunkActivity, PhotoManagerAnimationActivity::class.java))
                }

                else -> {
                    startActivity(
                        Intent(this, CleaningActivity::class.java).apply {
                            val list = junkExpandAdapter.getChoosePath()
                            putExtra("list", list.map { it.chilepath }.toTypedArray())
                            putExtra("size", list.sumOf { it.childSize })
                        }
                    )

                }
            }
            finish()
        }

    }

    private fun scanJunk() = lifecycleScope.launch(Dispatchers.Main) {

        var totalSize = 0L

        val list = arrayListOf<ChildBean>()
        async {
            val emptyFolder1 = FileHelp.getFileFolder(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM))
            val emptyFolder2 = FileHelp.getFileFolder(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS))
            val emptyFolder3 = FileHelp.getFileFolder(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS))
            val emptyFolder4 = FileHelp.getFileFolder(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES))
            val emptyFolder5 = FileHelp.getFileFolder(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES))
            val emptyFolder6 = FileHelp.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.forEach { l ->
                list.add(ChildBean(R.mipmap.kongwenjian, l.name, l.path, 1))
            }
            delay(Random.nextLong(1500, 2000))
        }.await()
        junkExpandAdapter.addChildData(0, list)


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


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

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

        binding.tvBtn.isVisible = true
        binding.tvBtn.isEnabled = true
    }


    override fun onDestroy() {
        super.onDestroy()
        junkExpandAdapter.animators.values.forEach {
            it.cancel()
        }
    }
}