package com.base.datarecovery.activity.repeat

import android.content.Context
import android.graphics.Color
import android.view.View
import androidx.activity.addCallback
import androidx.core.view.isVisible
import androidx.core.view.updatePadding
import androidx.lifecycle.lifecycleScope
import com.base.datarecovery.adapter.MediaAdapter
import com.base.datarecovery.ads.AdmobMaxHelper
import com.base.datarecovery.ads.AdmobMaxHelper.showDeleteAdSp
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.ConfigHelper
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.utils.SimilarHelper.calculateSimilar
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 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 (beanList.isNotEmpty()) {
            binding.progressBar.visibility = View.GONE
            binding.tvScanning.visibility = View.GONE
            binding.flScanning.visibility = View.GONE
            mediaAdapter.setData(beanList)
        }

        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,false) {
                        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 (showDeleteAdSp()) {
                    AdmobMaxHelper.admobMaxShowInterstitialAd(this@RepeatActivity,false) {
                        cleanFile()
                    }
                } else {
                    cleanFile()
                }
            }
        }
    }


    private fun cleanFile() {
        lifecycleScope.launch(Dispatchers.IO) {
            val cleanList = mediaAdapter.getSelectData().second
            cleanList.forEach {
                runCatching {
                    val file = File(it.path)
                    file.delete()
                }
            }
            launch(Dispatchers.Main) {
                mediaAdapter.removeData(cleanList)
                if (mediaAdapter.isEmptyData()) {
                    binding.llEmpty.isVisible = true
                    binding.tvSize.text = "0.0"
                    binding.tvUnit.text = "B"
                }
            }
        }
    }

    private fun initData() {
        if (beanList.isNotEmpty()) {
            return
        }

        lifecycleScope.launch(Dispatchers.IO) {

            val beanList = getSimilarList(this@RepeatActivity)

            launch(Dispatchers.Main) {
                binding.progressBar.visibility = View.GONE
                binding.tvScanning.visibility = View.GONE
                binding.flScanning.visibility = View.GONE
                mediaAdapter.setData(beanList)
                if (beanList.sumOf { it.beans.size } > 6 || ConfigHelper.mustShowNativeAd) {
                    AdmobMaxHelper.admobMaxShowNativeAd(this@RepeatActivity, binding.flAd)
                }
                binding.llEmpty.isVisible = beanList.isEmpty()
            }
        }

    }


    companion object {
        var beanList: ArrayList<MediaTimeBean> = ArrayList()
        fun getSimilarList(context: Context): List<MediaTimeBean> {
            val list = arrayListOf<MediaBean>()
            context.getImageMedia(list)

            val similarList = calculateSimilar(list)

            val beanList = similarList.map { map ->
                val time = File(map.key).lastModified().toFormatTime()
                MediaTimeBean(time = time, beans = map.value)
            }
            return beanList
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        beanList.clear()
    }

}