package com.base.datarecovery.activity.whatsapp

import android.content.Intent
import android.graphics.Color
import android.os.Environment
import androidx.activity.addCallback
import androidx.lifecycle.lifecycleScope
import com.base.datarecovery.R
import com.base.datarecovery.activity.ResultActivity
import com.base.datarecovery.adapter.WhatsAppCleanerAdapter
import com.base.datarecovery.ads.AdmobMaxHelper
import com.base.datarecovery.ads.admob.AdmobInterstitialUtils
import com.base.datarecovery.bean.ConstObject.WHATSAPP_CLEANER
import com.base.datarecovery.bean.WhatsAppCleanerBean
import com.base.datarecovery.databinding.ActivityWhatsAppCleanerBinding
import com.base.datarecovery.help.BaseActivity
import com.base.datarecovery.help.FileHelp.getDirFiles
import com.base.datarecovery.help.KotlinExt.toFormatSize
import com.base.datarecovery.help.PermissionHelp.checkStorePermission
import com.base.datarecovery.help.PermissionHelp.requestStorePermission
import com.base.datarecovery.utils.BarUtils
import com.base.datarecovery.utils.FileHexEx.isImage
import com.base.datarecovery.utils.FileHexEx.isVideo
import com.base.datarecovery.utils.LogEx
import com.base.datarecovery.view.DialogViews.showExitFunctionDialog
import com.base.datarecovery.view.DialogViews.showGerPermission
import com.google.gson.Gson
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.io.File

class WhatsAppCleanerActivity : BaseActivity<ActivityWhatsAppCleanerBinding>() {

    private val TAG = "WhatsAppCleanerActivity"
    private lateinit var adapter: WhatsAppCleanerAdapter

    override val binding: ActivityWhatsAppCleanerBinding by lazy {
        ActivityWhatsAppCleanerBinding.inflate(layoutInflater)
    }


    override fun initView() {
        BarUtils.setStatusBarLightMode(this, true)
        BarUtils.setStatusBarColor(this, Color.TRANSPARENT)

        adapter = WhatsAppCleanerAdapter {
            startActivity(Intent(this, WhatsAppMessageCleanActivity::class.java).apply {
                putExtra("PathList", Gson().toJson(it.subFile.toTypedArray()))
                putExtra("Tittle", it.tittle)
            })
            finish()
        }
        binding.rv.adapter = adapter

        if (checkStorePermission()) {
            initData()
        } else {
            showGerPermission(null, deny = {
                finishToMain()
            }, allow = {
                requestStorePermission(
                    launcher,
                    result = { flag ->
                        if (flag) {
                            initData()
                        } else {
                            finishToMain()
                        }
                    },
                )
            })
        }
    }

    override fun initListener() {
        binding.flBack.setOnClickListener {
            onBackPressedDispatcher.onBackPressed()
        }
        onBackPressedDispatcher.addCallback {
            showExitFunctionDialog { showAd ->
                if (showAd) {
                    AdmobMaxHelper.admobMaxShowInterstitialAd(this@WhatsAppCleanerActivity, false) {
                        finishToMain()
                    }
                } else {
                    finishToMain()
                }
            }
        }
        binding.tvTvGotIt.setOnClickListener {
            startActivity(Intent(this, ResultActivity::class.java).apply {
                putExtra("from", WHATSAPP_CLEANER)
            })
            finish()
        }

    }


    private fun initData() = lifecycleScope.launch(Dispatchers.IO) {

        val whatsAppRoot = File(Environment.getExternalStorageDirectory(), "Android/media/com.whatsapp/WhatsApp/Media/")
        LogEx.logDebug(TAG, whatsAppRoot.absolutePath)
        val list = arrayListOf<WhatsAppCleanerBean>()
        list.add(WhatsAppCleanerBean(R.mipmap.videomessages, "Video Messages"))
        list.add(WhatsAppCleanerBean(R.mipmap.imagemessages, "Image Messages"))
        list.add(WhatsAppCleanerBean(R.mipmap.audiomessages, "Audio Messages"))
        var totalSize = 0L
        whatsAppRoot.listFiles()?.forEach { file ->

            if (file.name == "WhatsApp Video") {
                LogEx.logDebug(TAG, "whatsapp file=${file.absolutePath}")
                val bean = list.find { it.tittle == "Video Messages" }
                val subFile = getDirFiles(file).filter { isVideo(it) }
                val size = subFile.sumOf { it.length() }
                bean?.size = size
                totalSize += size
                bean?.subFile = subFile.map { it.absolutePath }
//                subFile.forEach { path ->
//                    LogEx.logDebug(TAG, "path=$path")
//                }
            }
            if (file.name == "WhatsApp Images") {
                val bean = list.find { it.tittle == "Image Messages" }
                val subFile = getDirFiles(file).filter { isImage(it) }
                val size = subFile.sumOf { it.length() }
                bean?.size = size
                totalSize += size
                bean?.subFile = subFile.map { it.absolutePath }
            }
            if (file.name == "WhatsApp Audio") {
                val bean = list.find { it.tittle == "Audio Messages" }
                val subFile = getDirFiles(file).filter { it.name.contains(".mp3") }
                val size = subFile.sumOf { it.length() }
                bean?.size = size
                totalSize += size
                bean?.subFile = subFile.map { it.absolutePath }
            }
        }
        launch(Dispatchers.Main) {
            adapter.setData(list)
            val split = totalSize.toFormatSize().split(" ")
            binding.tvSize.text = split[0]
            binding.tvUnit.text = split[1]
        }
    }

}