package com.base.filerecoveryrecyclebin.activity.repeat

import android.graphics.Color
import android.view.View
import androidx.activity.addCallback
import androidx.core.view.updatePadding
import androidx.lifecycle.lifecycleScope
import com.base.filerecoveryrecyclebin.adapter.MediaAdapter
import com.base.filerecoveryrecyclebin.ads.AdmobMaxHelper
import com.base.filerecoveryrecyclebin.ads.admob.AdmobInterstitialUtils.showInterAdSp
import com.base.filerecoveryrecyclebin.bean.MediaBean
import com.base.filerecoveryrecyclebin.bean.MediaTimeBean
import com.base.filerecoveryrecyclebin.databinding.ActivityRepeatBinding
import com.base.filerecoveryrecyclebin.help.BaseActivity
import com.base.filerecoveryrecyclebin.help.ConfigHelper
import com.base.filerecoveryrecyclebin.help.KotlinExt.toFormatSize
import com.base.filerecoveryrecyclebin.help.KotlinExt.toFormatTime
import com.base.filerecoveryrecyclebin.help.MediaStoreHelp.getImageMedia
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.launch
import java.io.File

class RepeatActivity : BaseActivity<ActivityRepeatBinding>() {


    override val binding: ActivityRepeatBinding by lazy {
        ActivityRepeatBinding.inflate(layoutInflater)
    }
    private lateinit var mediaAdapter: MediaAdapter


    override fun initView() {
        BarUtils.setStatusBarLightMode(this, true)
        BarUtils.setStatusBarColor(this, Color.TRANSPARENT)
        binding.root.updatePadding(top = BarUtils.getStatusBarHeight())
        mediaAdapter = MediaAdapter {
            binding.ivSelectAll.isSelected = it.first
            binding.tvClean.isEnabled = it.second.isNotEmpty()
            runCatching {
                val split = it.second.sumOf { bean -> File(bean.path).length() }.toFormatSize().split(" ")
                binding.tvSize.text = split[0]
                binding.tvUnit.text = split[1]
            }
        }
        binding.rv.adapter = mediaAdapter

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

    override fun initListener() {
        onBackPressedDispatcher.addCallback {
            showExitFunctionDialog {
                if (it) {
                    AdmobMaxHelper.admobMaxShowInterstitialAd(this@RepeatActivity){
                        finishToMain()
                    }
                } else {
                    finishToMain()
                }

            }
        }
        binding.flBack.setOnClickListener {
            onBackPressedDispatcher.onBackPressed()
        }
        binding.llSelectAll.setOnClickListener {
            binding.ivSelectAll.isSelected = !binding.ivSelectAll.isSelected
            mediaAdapter.toggleAllSelect(binding.ivSelectAll.isSelected)
        }
        binding.tvClean.setOnClickListener {
            showDeletePermanentlyDialog {
                if (showInterAdSp()) {
                    AdmobMaxHelper.admobMaxShowInterstitialAd(this){
                        cleanFile()
                    }
                } else {
                    cleanFile()
                }
            }
        }
    }


    private fun cleanFile() {
        lifecycleScope.launch(Dispatchers.IO) {
            mediaAdapter.getSelectData().second.forEach {
                runCatching {
                    val file = File(it.path)
                    file.delete()
                }
            }
            initData()
        }
    }

    private fun initData() {

        lifecycleScope.launch(Dispatchers.IO) {
            val list = arrayListOf<MediaBean>()
            getImageMedia(list)

            val hashMap = HashMap<String, ArrayList<MediaBean>>()
            list.forEach {
                val time = it.time.toFormatTime()
                if (hashMap[time] == null) {
                    hashMap[time] = arrayListOf()
                }
                hashMap[time]?.add(it)
            }
            val beanList = hashMap.map { MediaTimeBean(it.key, it.value) }
            launch(Dispatchers.Main) {
                binding.progressBar.visibility = View.GONE
                mediaAdapter.setData(beanList)
                if (beanList.sumOf { it.beans.size } > 6 || ConfigHelper.mustShowNativeAd) {
                    AdmobMaxHelper.admobMaxShowNativeAd(this@RepeatActivity, binding.flAd)
                }
            }
        }

    }

}