package com.base.filerecoveryrecyclebin.activity.junkclean

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.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.AppPreferences
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())
        AdmobMaxHelper.admobMaxShowNativeAd(this, binding.idFlNative)
        junkExpandAdapter = JunkExpandAdapter { size ->
            if (size == 0L) {
                binding.tvBtn.text = "Got it"
                binding.tvBtn.isEnabled = true
                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 (scanFinish) {
                if (junkExpandAdapter.getAllChildItemCount() == 0) {
                    binding.tvBtn.visibility = View.VISIBLE
                    binding.llTwoBtn.visibility = View.GONE
                } else {
                    binding.tvBtn.isVisible = true
                    binding.tvBtn.isEnabled = true
                }
            }
        }
        binding.exRv.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.flFanhui.setOnClickListener {
            onBackPressedDispatcher.onBackPressed()
        }
        onBackPressedDispatcher.addCallback(object : OnBackPressedCallback(true) {
            override fun handleOnBackPressed() {
                showExitFunctionDialog(this@CleanJunkActivity) {
                    if (it) {
                        AdmobMaxHelper.admobMaxShowInterstitialAd(
                            this@CleanJunkActivity,
                            isLoading = false
                        ) {
                            finishToMain()
                        }
                    } else {
                        finishToMain()
                    }
                }
            }

        })
        binding.tvBtn.setOnClickListener {

            when (binding.tvBtn.text) {
                "Got it" -> {
                    val showJunkBtnAd =
                        AppPreferences.getInstance().getString("isGotItplayAd", "0").toInt()
                    if (showJunkBtnAd == 1) {
                        AdmobMaxHelper.admobMaxShowInterstitialAd(this, false) {
                            startActivity(
                                Intent(
                                    this@CleanJunkActivity,
                                    ResultActivity::class.java
                                ).apply {
                                    putExtra("clean_size", JUNK_CLEANER)
                                    putExtra("from", 0)
                                })
                            finish()
                        }
                    } else {
                        startActivity(
                            Intent(
                                this@CleanJunkActivity,
                                ResultActivity::class.java
                            ).apply {
                                putExtra("clean_size", JUNK_CLEANER)
                                putExtra("from", 0)
                            })
                        finish()
                    }

                }

                else -> {
                    val showJunkBtnAd =
                        AppPreferences.getInstance().getString("isGotItplayAd", "0").toInt()
                    if (showJunkBtnAd == 1) {
                        AdmobMaxHelper.admobMaxShowInterstitialAd(this, false) {
                            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()
                        }
                    } 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()
                    }
                }
            }

        }

        binding.tvGotIt2.setOnClickListener {
            startActivity(Intent(this@CleanJunkActivity, ResultActivity::class.java).apply {
                putExtra("clean_size", JUNK_CLEANER)
                putExtra("from", 0)
            })
            finish()
        }
        binding.tvDeepScan.setOnClickListener {
            startActivity(Intent(this, PhotoManagerAnimationActivity::class.java).apply {
                putExtra("tittle", "Deep Scan")
            })
            finish()
        }

    }

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

        var totalSize = 0L

        val list1 = async(Dispatchers.IO) {
            val list = arrayListOf<ChildBean>()
            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.filter { it.listFiles().isNullOrEmpty() }.forEach { l ->
                list.add(ChildBean(R.mipmap.kongwenjian, l.name, l.path, 1))
            }
            delay(Random.nextLong(1000, 1500))
            list
        }.await()
        junkExpandAdapter.addChildData(0, list1)


        val list2 = async(Dispatchers.IO) {
            val list = arrayListOf<ChildBean>()
            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(1000, 1500))
            list
        }.await()
        junkExpandAdapter.addChildData(1, list2)


        val list3 = async(Dispatchers.IO) {
            val list = arrayListOf<ChildBean>()
            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(1000, 1500))
            list
        }.await()
        junkExpandAdapter.addChildData(2, list3)


        val list4 = async(Dispatchers.IO) {
            val list = arrayListOf<ChildBean>()
            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(1000, 1500))
            list
        }.await()

        scanFinish = true
        junkExpandAdapter.addChildData(3, list4)


    }


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