package com.base.filerecoveryrecyclebin.activity.repeat

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.filerecoveryrecyclebin.adapter.MediaAdapter
import com.base.filerecoveryrecyclebin.ads.AdmobMaxHelper
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.MediaStoreHelp.updateMediaStore
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.LogEx
import com.base.filerecoveryrecyclebin.utils.SimilarHelper.calculateSimilar
import com.base.filerecoveryrecyclebin.view.DialogViews.showDeletePermanentlyDialog
import com.base.filerecoveryrecyclebin.view.DialogViews.showGerPermission
import com.base.filerecoveryrecyclebin.view.DialogViews.showTittleDescExitDialog
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withTimeout
import java.io.File

class RepeatActivity : BaseActivity<ActivityRepeatBinding>() {

    private val TAG = "RepeatActivity"

    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())

//        System.loadLibrary("opencv_java4")

        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 {
            if (binding.progressBar.isVisible) {
                showTittleDescExitDialog(
                    tittle = "Scan in Progress",
                    desc = "You are currently scanning for similar photos. Are you sure you want to exit?",
                    yBtn = "Continue", nBtn = "Exit"
                ) {
                    if (AdmobMaxHelper.showBackInterAdSp()) {
                        AdmobMaxHelper.admobMaxShowInterstitialAd(this@RepeatActivity, false) {
                            finishToMain()
                        }
                    } else {
                        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 (AdmobMaxHelper.showDeleteAdSp()) {
                    AdmobMaxHelper.admobMaxShowInterstitialAd(this, isLoading = false) {
                        cleanFile()
                    }
                } else {
                    cleanFile()
                }
            }
        }
    }


    private fun cleanFile() {
        similarPhotoDeleted = true
        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() {
        lifecycleScope.launch(Dispatchers.IO) {

            this@RepeatActivity.updateMediaStore()
            val list = arrayListOf<MediaBean>()
            getImageMedia(list)
            LogEx.logDebug(TAG, "list=${list.size}")
            list.reversed()


            val result = if (readySimilarList == null) {
                val similarList = HashMap<String, ArrayList<MediaBean>>()
                val startTime = System.currentTimeMillis()
                val endTime = withTimeout(15 * 1000) {
                    calculateSimilar(list, similarList)
                    System.currentTimeMillis()
                }
                val spendTime = endTime - startTime
                LogEx.logDebug(TAG, "spendTime=$spendTime startTime=$startTime endTime=$endTime")
                similarList
            } else {
                readySimilarList ?: hashMapOf()
            }

            val beanList = result.map { map ->
                val time = File(map.key).lastModified().toFormatTime()
                MediaTimeBean(time = time, beans = map.value)
            }
            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 readySimilarList: HashMap<String, ArrayList<MediaBean>>? = null
        var similarPhotoDeleted: Boolean = false
    }

}