package com.base.filerecoveryrecyclebin.activity.screenshot

import android.annotation.SuppressLint
import android.graphics.Color
import android.os.Environment
import androidx.activity.addCallback
import androidx.core.view.updatePadding
import androidx.lifecycle.lifecycleScope
import com.base.filerecoveryrecyclebin.adapter.ScreenShotAdapter
import com.base.filerecoveryrecyclebin.ads.admob.AdmobInterstitialUtils
import com.base.filerecoveryrecyclebin.ads.admob.AdmobInterstitialUtils.showInterAdSp
import com.base.filerecoveryrecyclebin.ads.admob.AdmobNativeUtils
import com.base.filerecoveryrecyclebin.bean.ScreenPhotoBean
import com.base.filerecoveryrecyclebin.bean.ScreenshotBean
import com.base.filerecoveryrecyclebin.databinding.ActivityScreenShotBinding
import com.base.filerecoveryrecyclebin.help.BaseActivity
import com.base.filerecoveryrecyclebin.help.ConfigHelper
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.view.DialogViews.showDeletePermanentlyDialog
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.launch
import java.io.File
import java.text.SimpleDateFormat
import java.util.Locale
import kotlin.collections.HashSet

class ScreenShotActivity : BaseActivity<ActivityScreenShotBinding>() {

    private lateinit var screenShotAdapter: ScreenShotAdapter

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

    override fun initView() {
        BarUtils.setStatusBarLightMode(this, true)
        BarUtils.setStatusBarColor(this, Color.TRANSPARENT)
        binding.root.updatePadding(top = BarUtils.getStatusBarHeight())

        screenShotAdapter = ScreenShotAdapter { size ->
            setCleanUpUi(size)
        }

        binding.rv.adapter = screenShotAdapter

        if (checkStorePermission()) {
            initData()
        } else {
            dialog = showGerPermission("Storage Permission Required",
                "This feature requires access to your storage to scan your files and clean up screenshots. 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, result = { flag ->
                        if (flag) initData() else finishToMain()
                    })
                })
        }

    }


    @SuppressLint("SetTextI18n")

    private fun setCleanUpUi(size: Int) {
        if (size > 0) {
            binding.tvClean.isEnabled = true
            binding.tvClean.text = "CLEAN(${size})"
        } else {
            binding.tvClean.isEnabled = false
            binding.tvClean.text = "CLEAN"
        }
        binding.llSelectAll.isSelected = screenShotAdapter.isAllSelect()
    }

    private fun initData() = lifecycleScope.launch(Dispatchers.IO) {
        val list = getScreenshotBean()
        launch(Dispatchers.Main) {
            screenShotAdapter.setData(list)
            val size = list.sumOf { it.screenPhotoBean.sumOf { ss -> ss.file.length() } }
            val sizeF = size.toFormatSize().split(" ")
            binding.tvSize.text = sizeF[0]
            binding.tvUnit.text = sizeF[1]
            if (list.sumOf { it.screenPhotoBean.size } > 6 || ConfigHelper.mustShowNativeAd) {
                AdmobNativeUtils.showNativeAd(this@ScreenShotActivity, binding.flAd)
            }
        }
    }

    @SuppressLint("SetTextI18n")
    override fun initListener() {
        binding.flBack.setOnClickListener {
            onBackPressedDispatcher.onBackPressed()
        }
        onBackPressedDispatcher.addCallback {
            showExitFunctionDialog {
                if (it) {
                    AdmobInterstitialUtils.showInterstitialAd(this@ScreenShotActivity) {
                        finishToMain()
                    }
                } else {
                    finishToMain()
                }

            }
        }


        binding.llSelectAll.setOnClickListener {
            binding.llSelectAll.isSelected = !binding.llSelectAll.isSelected
            screenShotAdapter.toggleSelect(binding.llSelectAll.isSelected)
            val size = screenShotAdapter.getSelectDataSize()
            setCleanUpUi(size)
        }
        binding.tvClean.setOnClickListener {

            showDeletePermanentlyDialog {
                if (showInterAdSp()) {
                    AdmobInterstitialUtils.showInterstitialAd(this) {
                        cleanFile()
                    }
                } else {
                    cleanFile()
                }

            }
        }
    }

    private fun cleanFile() {
        val files = screenShotAdapter.getSelectData()
        lifecycleScope.launch(Dispatchers.IO) {
            async {
                files.forEach { screenFile ->
                    runCatching {
                        val file = screenFile.file
                        if (file.exists()) file.delete()
                    }
                }
            }.await()
            launch(Dispatchers.Main) {
                binding.tvClean.text = "CLEAN"
                screenShotAdapter.removeData(files)
                val split = screenShotAdapter.getAllData().sumOf { it.file.length() }.toFormatSize().split(" ")
                binding.tvSize.text = split[0]
                binding.tvUnit.text = split[1]
                setCleanUpUi(0)
            }
        }
    }

    private fun getScreenshotBean(): ArrayList<ScreenshotBean> {
        val dcim = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM)
        val screenFiles = FileHelp.getDirFiles(dcim)
        val hash = HashMap<String, HashSet<File>>()
        val formatter = SimpleDateFormat("yyyy/MM", Locale.getDefault())

        screenFiles.forEach { file ->
            val time = formatter.format(file.lastModified())
            if (hash[time] == null) {
                hash[time] = HashSet()
            }
            val set = hash[time]
            set?.add(file)
        }

        val beans = arrayListOf<ScreenshotBean>()
        hash.forEach { (t, u) ->
            val arrayList = arrayListOf<ScreenPhotoBean>()
            val mapList = u.map { file -> ScreenPhotoBean(file) }
            arrayList.addAll(mapList)
            beans.add(ScreenshotBean(t, arrayList))
        }
        return beans
    }
}