package rowedto.jockeyedto.sheetedto.atticedto.jobedto.basinedto.civilianedto

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.FaithedtoBinding
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import rowedto.jockeyedto.sheetedto.balsamedto.formaledto.orientationedto.Patedto.showDeletePermanentlyDialog
import rowedto.jockeyedto.sheetedto.balsamedto.formaledto.orientationedto.Patedto.showExitFunctionDialog
import rowedto.jockeyedto.sheetedto.balsamedto.formaledto.orientationedto.Patedto.showGerPermission
import rowedto.jockeyedto.sheetedto.debutedto.revolutionaryedto.Cunningedto
import rowedto.jockeyedto.sheetedto.debutedto.revolutionaryedto.Sisteredto
import rowedto.jockeyedto.sheetedto.knewedto.economicedto.copyrightedto.Affairedto.getImageMedia
import rowedto.jockeyedto.sheetedto.knewedto.economicedto.copyrightedto.Celledto
import rowedto.jockeyedto.sheetedto.knewedto.economicedto.copyrightedto.Crossingedto
import rowedto.jockeyedto.sheetedto.knewedto.economicedto.copyrightedto.Studiededto.checkStorePermission
import rowedto.jockeyedto.sheetedto.knewedto.economicedto.copyrightedto.Studiededto.requestStorePermission
import rowedto.jockeyedto.sheetedto.knewedto.economicedto.copyrightedto.Suitcaseedto.toFormatSize
import rowedto.jockeyedto.sheetedto.knewedto.economicedto.copyrightedto.Suitcaseedto.toFormatTime
import rowedto.jockeyedto.sheetedto.meadowedto.naturaledto.idealedto.Complainedto
import rowedto.jockeyedto.sheetedto.raceedto.pavementedto.Spareedto
import rowedto.jockeyedto.sheetedto.raceedto.pavementedto.Understandingedto.calculateSimilar
import rowedto.jockeyedto.sheetedto.strangeedto.pyramidedto.particlesedto.Scandaledto
import rowedto.jockeyedto.sheetedto.strangeedto.pyramidedto.particlesedto.Scandaledto.showDeleteAdSp
import java.io.File

class Quarteredto : Crossingedto<FaithedtoBinding>() {


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


    override fun initView() {
        Spareedto.setStatusBarLightMode(this, true)
        Spareedto.setStatusBarColor(this, Color.TRANSPARENT)
        binding.root.updatePadding(top = Spareedto.getStatusBarHeight())
        mediaAdapter = Complainedto {
            binding.captureedto.isSelected = it.first
            binding.dueedto.isEnabled = it.second.isNotEmpty()
            runCatching {
                val split = it.second.sumOf { bean -> File(bean.path).length() }.toFormatSize().split(" ")
                binding.bulletinedto.text = split[0]
                binding.figureedto.text = split[1]
            }
        }
        binding.funeraledto.adapter = mediaAdapter
        if (beanList.isNotEmpty()) {
            binding.brushedto.visibility = View.GONE
            binding.conversationedto.visibility = View.GONE
            binding.mayoredto.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) {
                    Scandaledto.admobMaxShowInterstitialAd(this@Quarteredto,false) {
                        finishToMain()
                    }
                } else {
                    finishToMain()
                }

            }
        }
        binding.concentrateedto.setOnClickListener {
            onBackPressedDispatcher.onBackPressed()
        }
        binding.noveledto.setOnClickListener {
            binding.captureedto.isSelected = !binding.captureedto.isSelected
            mediaAdapter.toggleAllSelect(binding.captureedto.isSelected)
        }
        binding.dueedto.setOnClickListener {
            showDeletePermanentlyDialog {
                if (showDeleteAdSp()) {
                    Scandaledto.admobMaxShowInterstitialAd(this@Quarteredto,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.strokeedto.isVisible = true
                    binding.bulletinedto.text = "0.0"
                    binding.figureedto.text = "B"
                }
            }
        }
    }

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

        lifecycleScope.launch(Dispatchers.IO) {

            val beanList = getSimilarList(this@Quarteredto)

            launch(Dispatchers.Main) {
                binding.brushedto.visibility = View.GONE
                binding.conversationedto.visibility = View.GONE
                binding.mayoredto.visibility = View.GONE
                mediaAdapter.setData(beanList)
                if (beanList.sumOf { it.beans.size } > 6 || Celledto.mustShowNativeAd) {
                    Scandaledto.admobMaxShowNativeAd(this@Quarteredto, binding.breatheedto)
                }
                binding.strokeedto.isVisible = beanList.isEmpty()
            }
        }

    }


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

            val similarList = calculateSimilar(list)

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

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

}