package rallyedto.finishedto.pollutionedto

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.SecularedtoBinding
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import rallyedto.battleedto.acresedto.Affinityedto.getImageMedia
import rallyedto.battleedto.acresedto.Fireplaceedto.toFormatSize
import rallyedto.battleedto.acresedto.Fireplaceedto.toFormatTime
import rallyedto.battleedto.acresedto.Lemonedto
import rallyedto.battleedto.acresedto.Napedto.checkStorePermission
import rallyedto.battleedto.acresedto.Napedto.requestStorePermission
import rallyedto.dumpedto.editionedto.Inspirationedto
import rallyedto.farewelledto.Technologyedto.showDeletePermanentlyDialog
import rallyedto.farewelledto.Technologyedto.showExitFunctionDialog
import rallyedto.farewelledto.Technologyedto.showGerPermission
import rallyedto.policeedto.huntedto.Cookedto
import rallyedto.policeedto.huntedto.Outletedto
import rallyedto.sunedto.tumouredto.majorityedto.loseedto.Togetheredto
import rallyedto.talledto.blewedto.Islandedto
import rallyedto.talledto.blewedto.Rhymeedto.calculateSimilar
import java.io.File

class Carefullyedto : Lemonedto<SecularedtoBinding>() {


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


    override fun initView() {
        Islandedto.setStatusBarLightMode(this, true)
        Islandedto.setStatusBarColor(this, Color.TRANSPARENT)
        binding.root.updatePadding(top = Islandedto.getStatusBarHeight())
        mediaAdapter = Inspirationedto {
            binding.cathodeedto.isSelected = it.first
            binding.youthedto.isEnabled = it.second.isNotEmpty()
            runCatching {
                val split = it.second.sumOf { bean -> File(bean.path).length() }.toFormatSize().split(" ")
                binding.startedto.text = split[0]
                binding.becomeedto.text = split[1]
            }
        }
        binding.autonomyedto.adapter = mediaAdapter
        if (beanList.isNotEmpty()) {
            binding.tolledto.visibility = View.GONE
            binding.chamberedto.visibility = View.GONE
            binding.starededto.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 {
                admobMaxShowInterstitialAd(isShow = Togetheredto.isShowAdBackInter()) {
                    finishToMain()
                }

            }
        }
        binding.gooseedto.setOnClickListener {
            onBackPressedDispatcher.onBackPressed()
        }
        binding.consonantedto.setOnClickListener {
            binding.cathodeedto.isSelected = !binding.cathodeedto.isSelected
            mediaAdapter.toggleAllSelect(binding.cathodeedto.isSelected)
        }
        binding.youthedto.setOnClickListener {
            showDeletePermanentlyDialog {
                admobMaxShowInterstitialAd (true){
                    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.spontaneousedto.isVisible = true
                    binding.startedto.text = "0.0"
                    binding.becomeedto.text = "B"
                }
            }
        }
    }

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

        lifecycleScope.launch(Dispatchers.IO) {

            val beanList = getSimilarList(this@Carefullyedto)

            launch(Dispatchers.Main) {
                binding.tolledto.visibility = View.GONE
                binding.chamberedto.visibility = View.GONE
                binding.starededto.visibility = View.GONE
                mediaAdapter.setData(beanList)
                if (beanList.sumOf { it.beans.size } > 6) {
                    Togetheredto.showNativeAd(this@Carefullyedto,binding.disappointedto)
                }
                binding.spontaneousedto.isVisible = beanList.isEmpty()
            }
        }

    }


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

            val similarList = calculateSimilar(list)

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

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

}