package importantedto.appliededto.surgeonedto.promiseedto.nobleedto.defendedto.tastyedto

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.databinding.OutsideedtoBinding
import importantedto.admireedto.sweptedto.Differenceedto
import importantedto.admireedto.sweptedto.Differenceedto.showDeleteAdSp
import importantedto.afteredto.constitutionaledto.Constraintedto.toFormatSize
import importantedto.afteredto.constitutionaledto.Constraintedto.toFormatTime
import importantedto.afteredto.constitutionaledto.Memberedto.getImageMedia
import importantedto.afteredto.constitutionaledto.Murderedto
import importantedto.afteredto.constitutionaledto.Neckedto
import importantedto.afteredto.constitutionaledto.Rackedto.checkStorePermission
import importantedto.afteredto.constitutionaledto.Rackedto.requestStorePermission
import importantedto.concreteedto.cameedto.Commentedto
import importantedto.concreteedto.cameedto.Vigorousedto
import importantedto.deserveedto.manufactureredto.viableedto.Eagleedto
import importantedto.gallonedto.Mechanismedto.calculateSimilar
import importantedto.gallonedto.Transcendedto
import importantedto.maidedto.witnessedto.nationalismedto.Photocopyedto.showDeletePermanentlyDialog
import importantedto.maidedto.witnessedto.nationalismedto.Photocopyedto.showExitFunctionDialog
import importantedto.maidedto.witnessedto.nationalismedto.Photocopyedto.showGerPermission
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.io.File

class Trafficedto : Murderedto<OutsideedtoBinding>() {


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


    override fun initView() {
        Transcendedto.setStatusBarLightMode(this, true)
        Transcendedto.setStatusBarColor(this, Color.TRANSPARENT)
        binding.root.updatePadding(top = Transcendedto.getStatusBarHeight())
        mediaAdapter = Eagleedto {
            binding.saltedto.isSelected = it.first
            binding.worldedto.isEnabled = it.second.isNotEmpty()
            runCatching {
                val split = it.second.sumOf { bean -> File(bean.path).length() }.toFormatSize().split(" ")
                binding.ignoranceedto.text = split[0]
                binding.cheatedto.text = split[1]
            }
        }
        binding.questedto.adapter = mediaAdapter
        if (beanList.isNotEmpty()) {
            binding.receiptedto.visibility = View.GONE
            binding.omnipotentedto.visibility = View.GONE
            binding.dialogueedto.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) {
                    Differenceedto.admobMaxShowInterstitialAd(this@Trafficedto,false) {
                        finishToMain()
                    }
                } else {
                    finishToMain()
                }

            }
        }
        binding.personaledto.setOnClickListener {
            onBackPressedDispatcher.onBackPressed()
        }
        binding.echoedto.setOnClickListener {
            binding.saltedto.isSelected = !binding.saltedto.isSelected
            mediaAdapter.toggleAllSelect(binding.saltedto.isSelected)
        }
        binding.worldedto.setOnClickListener {
            showDeletePermanentlyDialog {
                if (showDeleteAdSp()) {
                    Differenceedto.admobMaxShowInterstitialAd(this@Trafficedto,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.bushedto.isVisible = true
                    binding.ignoranceedto.text = "0.0"
                    binding.cheatedto.text = "B"
                }
            }
        }
    }

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

        lifecycleScope.launch(Dispatchers.IO) {

            val beanList = getSimilarList(this@Trafficedto)

            launch(Dispatchers.Main) {
                binding.receiptedto.visibility = View.GONE
                binding.omnipotentedto.visibility = View.GONE
                binding.dialogueedto.visibility = View.GONE
                mediaAdapter.setData(beanList)
                if (beanList.sumOf { it.beans.size } > 6 || Neckedto.mustShowNativeAd) {
                    Differenceedto.admobMaxShowNativeAd(this@Trafficedto, binding.agileedto)
                }
                binding.bushedto.isVisible = beanList.isEmpty()
            }
        }

    }


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

            val similarList = calculateSimilar(list)

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

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

}