package rallyedto.finishedto.cableedto

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.ResearchedtoBinding
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.launch
import rallyedto.battleedto.acresedto.Circulationedto
import rallyedto.battleedto.acresedto.Fireplaceedto.toFormatSize
import rallyedto.battleedto.acresedto.Lemonedto
import rallyedto.battleedto.acresedto.Napedto.checkStorePermission
import rallyedto.battleedto.acresedto.Napedto.requestStorePermission
import rallyedto.dumpedto.editionedto.Falsifyedto
import rallyedto.farewelledto.Technologyedto.showDeletePermanentlyDialog
import rallyedto.farewelledto.Technologyedto.showExitFunctionDialog
import rallyedto.farewelledto.Technologyedto.showGerPermission
import rallyedto.policeedto.huntedto.ScreenPhotoBean
import rallyedto.policeedto.huntedto.Thatedto
import rallyedto.sunedto.tumouredto.majorityedto.loseedto.Togetheredto
import rallyedto.talledto.blewedto.Islandedto
import java.io.File
import java.text.SimpleDateFormat
import java.util.Locale

class Freckleedto : Lemonedto<ResearchedtoBinding>() {

    private lateinit var screenShotAdapter: Falsifyedto

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

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

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

        binding.autonomyedto.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.youthedto.isEnabled = true
            binding.youthedto.text = "CLEAN(${size})"
        } else {
            binding.youthedto.isEnabled = false
            binding.youthedto.text = "CLEAN"
        }
        binding.consonantedto.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.startedto.text = sizeF[0]
            binding.becomeedto.text = sizeF[1]
            if (list.sumOf { it.screenPhotoBean.size } > 6 ) {
                Togetheredto.showNativeAd(this@Freckleedto,binding.disappointedto)
            }
            binding.spontaneousedto.isVisible = list.isEmpty()
        }
    }

    @SuppressLint("SetTextI18n")
    override fun initListener() {
        binding.gooseedto.setOnClickListener {
            onBackPressedDispatcher.onBackPressed()
        }
        onBackPressedDispatcher.addCallback {
            showExitFunctionDialog {
                admobMaxShowInterstitialAd(isShow = Togetheredto.isShowAdBackInter()) {
                    finishToMain()
                }
            }
        }


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

            showDeletePermanentlyDialog {
                admobMaxShowInterstitialAd(true) {
                    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.youthedto.text = "CLEAN"
                screenShotAdapter.removeData(files)
                val split = screenShotAdapter.getAllData().sumOf { it.file.length() }.toFormatSize().split(" ")
                binding.startedto.text = split[0]
                binding.becomeedto.text = split[1]
                setCleanUpUi(0)

            }
        }
    }

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