package com.base.datarecovery.activity

import android.graphics.Color
import android.icu.util.MeasureUnit
import android.view.View
import androidx.activity.addCallback
import androidx.core.view.updatePadding
import androidx.lifecycle.lifecycleScope
import com.base.datarecovery.adapter.MediaAdapter
import com.base.datarecovery.adapter.MediaSubAdapter
import com.base.datarecovery.ads.AdmobInterstitialUtils
import com.base.datarecovery.bean.MediaBean
import com.base.datarecovery.bean.MediaTimeBean
import com.base.datarecovery.databinding.ActivityRepeatBinding
import com.base.datarecovery.help.BaseActivity
import com.base.datarecovery.help.KotlinExt.toFormatSize
import com.base.datarecovery.help.KotlinExt.toFormatTime
import com.base.datarecovery.help.MediaStoreHelp.getImageMedia
import com.base.datarecovery.help.PermissionHelp.checkStorePermission
import com.base.datarecovery.help.PermissionHelp.requestStorePermission
import com.base.datarecovery.utils.BarUtils
import com.base.datarecovery.view.DialogViews.showDeletePermanentlyDialog
import com.base.datarecovery.view.DialogViews.showExitFunctionDialog
import com.base.datarecovery.view.DialogViews.showGerPermission
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import org.jacoco.core.internal.analysis.filter.IFilter
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 {
                AdmobInterstitialUtils.showInterstitialAd(this@RepeatActivity) {
                    finishToMain()
                }
            }
        }
        binding.flBack.setOnClickListener {
            onBackPressedDispatcher.onBackPressed()
        }
        binding.llSelectAll.setOnClickListener {
            binding.ivSelectAll.isSelected = !binding.ivSelectAll.isSelected
            mediaAdapter.toggleAllSelect(binding.ivSelectAll.isSelected)
        }
        binding.tvClean.setOnClickListener {
            showDeletePermanentlyDialog {
                AdmobInterstitialUtils.showInterstitialAd(this) {
                    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)
            }
        }

    }

}