package importantedto.appliededto.surgeonedto.promiseedto.rapeedto

import android.annotation.SuppressLint
import android.graphics.Color
import android.os.Environment
import androidx.activity.addCallback
import androidx.core.view.isVisible
import androidx.core.view.updatePadding
import androidx.lifecycle.lifecycleScope
import com.base.datarecovery.databinding.HearedtoBinding
import importantedto.admireedto.sweptedto.Differenceedto
import importantedto.admireedto.sweptedto.Differenceedto.showDeleteAdSp
import importantedto.afteredto.constitutionaledto.Concessionedto
import importantedto.afteredto.constitutionaledto.Constraintedto.toFormatSize
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.Oxygenedto
import importantedto.concreteedto.cameedto.ScreenPhotoBean
import importantedto.deserveedto.manufactureredto.viableedto.Sumedto
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.async
import kotlinx.coroutines.launch
import java.io.File
import java.text.SimpleDateFormat
import java.util.Locale

class Boardedto : Murderedto<HearedtoBinding>() {

    private lateinit var screenShotAdapter: Sumedto

    override val binding: HearedtoBinding by lazy {
        HearedtoBinding.inflate(layoutInflater)
    }

    override fun initView() {
        Transcendedto.setStatusBarLightMode(this, true)
        Transcendedto.setStatusBarColor(this, Color.TRANSPARENT)
        binding.root.updatePadding(top = Transcendedto.getStatusBarHeight())

        screenShotAdapter = Sumedto { size ->
            setCleanUpUi(size)
        }

        binding.questedto.adapter = screenShotAdapter

        if (checkStorePermission()) {
            initData()
        } else {
            dialog = showGerPermission("Storage Permission Required",
                "This feature requires access to your storage to scan your files and clean up screenshots. 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 = { flag ->
                        if (flag) initData() else finishToMain()
                    })
                })
        }

    }


    @SuppressLint("SetTextI18n")

    private fun setCleanUpUi(size: Int) {
        if (size > 0) {
            binding.worldedto.isEnabled = true
            binding.worldedto.text = "CLEAN(${size})"
        } else {
            binding.worldedto.isEnabled = false
            binding.worldedto.text = "CLEAN"
        }
        binding.echoedto.isSelected = screenShotAdapter.isAllSelect()
    }

    private fun initData() = lifecycleScope.launch(Dispatchers.IO) {
        val list = getScreenshotBean()
        launch(Dispatchers.Main) {
            screenShotAdapter.setData(list)
            val size = list.sumOf { it.screenPhotoBean.sumOf { ss -> ss.file.length() } }
            val sizeF = size.toFormatSize().split(" ")
            binding.ignoranceedto.text = sizeF[0]
            binding.cheatedto.text = sizeF[1]
            if (list.sumOf { it.screenPhotoBean.size } > 6 || Neckedto.mustShowNativeAd) {
                Differenceedto.admobMaxShowNativeAd(this@Boardedto, binding.agileedto)
            }
            binding.bushedto.isVisible = list.isEmpty()
        }
    }

    @SuppressLint("SetTextI18n")
    override fun initListener() {
        binding.personaledto.setOnClickListener {
            onBackPressedDispatcher.onBackPressed()
        }
        onBackPressedDispatcher.addCallback {
            showExitFunctionDialog {
                if (it) {
                    Differenceedto.admobMaxShowInterstitialAd(this@Boardedto, false) {
                        finishToMain()
                    }
                } else {
                    finishToMain()
                }

            }
        }


        binding.echoedto.setOnClickListener {
            binding.echoedto.isSelected = !binding.echoedto.isSelected
            screenShotAdapter.toggleSelect(binding.echoedto.isSelected)
            val size = screenShotAdapter.getSelectDataSize()
            setCleanUpUi(size)
        }
        binding.worldedto.setOnClickListener {

            showDeletePermanentlyDialog {
                if (showDeleteAdSp()) {
                    Differenceedto.admobMaxShowInterstitialAd(this, false) {
                        cleanFile()
                    }
                } else {
                    cleanFile()
                }

            }
        }
    }

    private fun cleanFile() {
        val files = screenShotAdapter.getSelectData()
        lifecycleScope.launch(Dispatchers.IO) {
            async {
                files.forEach { screenFile ->
                    runCatching {
                        val file = screenFile.file
                        if (file.exists()) file.delete()
                    }
                }
            }.await()
            launch(Dispatchers.Main) {
                binding.worldedto.text = "CLEAN"
                screenShotAdapter.removeData(files)
                val split = screenShotAdapter.getAllData().sumOf { it.file.length() }.toFormatSize().split(" ")
                binding.ignoranceedto.text = split[0]
                binding.cheatedto.text = split[1]
                setCleanUpUi(0)
            }
        }
    }

    private fun getScreenshotBean(): ArrayList<Oxygenedto> {
        val dcim = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM)
        val screenFiles = Concessionedto.getDirFiles(dcim)
        val hash = HashMap<String, HashSet<File>>()
        val formatter = SimpleDateFormat("yyyy/MM", Locale.getDefault())

        screenFiles.forEach { file ->
            val time = formatter.format(file.lastModified())
            if (hash[time] == null) {
                hash[time] = HashSet()
            }
            val set = hash[time]
            set?.add(file)
        }

        val beans = arrayListOf<Oxygenedto>()
        hash.forEach { (t, u) ->
            val arrayList = arrayListOf<ScreenPhotoBean>()
            val mapList = u.map { file -> ScreenPhotoBean(file) }
            arrayList.addAll(mapList)
            beans.add(Oxygenedto(t, arrayList))
        }
        return beans
    }
}