package com.base.filerecoveryrecyclebin.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.filerecoveryrecyclebin.R
import com.base.filerecoveryrecyclebin.adapter.WhatsAppCleanerAdapter
import com.base.filerecoveryrecyclebin.ads.AdmobMaxHelper
import com.base.filerecoveryrecyclebin.bean.WhatsAppCleanerBean
import com.base.filerecoveryrecyclebin.databinding.ActivityWhatsAppCleanerBinding
import com.base.filerecoveryrecyclebin.help.BaseActivity
import com.base.filerecoveryrecyclebin.help.FileHelp.getDirFiles
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.FileHexEx.isImage
import com.base.filerecoveryrecyclebin.utils.FileHexEx.isVideo
import com.base.filerecoveryrecyclebin.utils.LogEx
import com.base.filerecoveryrecyclebin.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
    private val whatsAppMediaDir = "${Environment.getExternalStorageDirectory()}/Android/media/com.whatsapp/WhatsApp/Media/"


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

    override fun initView() {
        setupStatusBar()
        setupAdapter()
        checkAndRequestPermissions()
        showNativeAd()
    }

    private fun setupStatusBar() {
        BarUtils.setStatusBarLightMode(this, true)
        BarUtils.setStatusBarColor(this, Color.TRANSPARENT)
    }

    private fun setupAdapter() {
        adapter = WhatsAppCleanerAdapter { item ->
            navigateToWhatsAppMessageCleanActivity(item)
        }
        binding.rv.adapter = adapter
    }

    private fun checkAndRequestPermissions() {
        if (checkStorePermission()) {
            initData()
        } else {
            requestStoragePermissionWithDialog()
        }
    }

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

    private fun navigateToWhatsAppMessageCleanActivity(item: WhatsAppCleanerBean) {
        val intent = Intent(this, WhatsAppMessageCleanActivity::class.java).apply {
            putExtra("PathList", Gson().toJson(item.subFile.toTypedArray()))
            putExtra("Tittle", item.tittle)
        }
        startActivity(intent)
        finish()
    }

    private fun showNativeAd() {
        AdmobMaxHelper.admobMaxShowNativeAd(this, binding.flAd, 0)
    }

    override fun initListener() {
        setupBackButton()
    }

    private fun setupBackButton() {
        binding.flBack.setOnClickListener {
            onBackPressedDispatcher.onBackPressed()
        }
        onBackPressedDispatcher.addCallback {
            showInterstitialAdAndFinish()

        }
    }

    private fun showInterstitialAdAndFinish() {
        AdmobMaxHelper.admobMaxShowInterstitialAd(this) {
            finishToMain()
        }
    }

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


        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
        File(whatsAppMediaDir).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)
            updateTotalSizeUI(list)
        }
    }

    private fun updateTotalSizeUI(list: List<WhatsAppCleanerBean>) {
        val totalSize = list.sumOf { it.size }
        val formattedSize = totalSize.toFormatSize()
        binding.tvSize.text = formattedSize.split(" ")[0]
        binding.tvUnit.text = formattedSize.split(" ")[1]
    }
}