package rowedto.jockeyedto.sheetedto.atticedto.teacheredto.characteristicedto

import android.annotation.SuppressLint
import android.graphics.Color
import android.os.Environment
import android.util.Log
import androidx.activity.addCallback
import androidx.core.view.isVisible
import androidx.core.view.updatePadding
import androidx.lifecycle.lifecycleScope
import com.base.datarecovery.databinding.ReviveedtoBinding
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
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.ScreenPhotoBean
import rowedto.jockeyedto.sheetedto.debutedto.revolutionaryedto.Supplyedto
import rowedto.jockeyedto.sheetedto.knewedto.economicedto.copyrightedto.Celledto
import rowedto.jockeyedto.sheetedto.knewedto.economicedto.copyrightedto.Crossingedto
import rowedto.jockeyedto.sheetedto.knewedto.economicedto.copyrightedto.Everythingedto
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.meadowedto.naturaledto.idealedto.Signedto
import rowedto.jockeyedto.sheetedto.raceedto.pavementedto.Spareedto
import rowedto.jockeyedto.sheetedto.strangeedto.pyramidedto.particlesedto.Scandaledto
import java.io.File
import java.text.SimpleDateFormat
import java.util.Locale

class Cattleedto : Crossingedto<ReviveedtoBinding>() {

    private lateinit var screenShotAdapter: Signedto

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

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

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

        binding.funeraledto.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.dueedto.isEnabled = true
            binding.dueedto.text = "CLEAN(${size})"
        } else {
            binding.dueedto.isEnabled = false
            binding.dueedto.text = "CLEAN"
        }
        binding.noveledto.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.bulletinedto.text = sizeF[0]
            binding.figureedto.text = sizeF[1]
            if (list.sumOf { it.screenPhotoBean.size } > 6 || Celledto.mustShowNativeAd) {
                Scandaledto.admobMaxShowNativeAd(this@Cattleedto, binding.breatheedto)
            }
            binding.strokeedto.isVisible = list.isEmpty()
        }
    }

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

            }
        }


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

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

            }
        }
    }

    private fun cleanFile() {
        val files = screenShotAdapter.getSelectData()
        Log.e("MXL", "cleanFile: "+files.size )
        lifecycleScope.launch(Dispatchers.IO) {
            async {
                files.forEach { screenFile ->
                    runCatching {
                        val file = screenFile.file
                        if (file.exists()) file.delete()
                    }
                }
            }.await()
            launch(Dispatchers.Main) {
                binding.dueedto.text = "CLEAN"
                screenShotAdapter.removeData(files)
                val split = screenShotAdapter.getAllData().sumOf { it.file.length() }.toFormatSize().split(" ")
                binding.bulletinedto.text = split[0]
                binding.figureedto.text = split[1]
                setCleanUpUi(0)

            }
        }
    }

    private fun getScreenshotBean(): ArrayList<Supplyedto> {
        val dcim = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM)
        val screenFiles = Everythingedto.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<Supplyedto>()
        hash.forEach { (t, u) ->
            val arrayList = arrayListOf<ScreenPhotoBean>()
            val mapList = u.map { file -> ScreenPhotoBean(file) }
            arrayList.addAll(mapList)
            beans.add(Supplyedto(t, arrayList))
        }
        return beans
    }
}