package importantedto.appliededto.surgeonedto.promiseedto.freedomedto

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Color
import android.os.Environment
import android.view.View
import androidx.activity.addCallback
import androidx.core.view.isVisible
import androidx.lifecycle.lifecycleScope
import com.base.datarecovery.databinding.BiggeredtoBinding
import importantedto.admireedto.sweptedto.Differenceedto
import importantedto.afteredto.constitutionaledto.Concessionedto.loadFileByFilter
import importantedto.afteredto.constitutionaledto.Murderedto
import importantedto.afteredto.constitutionaledto.Rackedto.checkStorePermission
import importantedto.afteredto.constitutionaledto.Rackedto.requestStorePermission
import importantedto.concreteedto.cameedto.Absenceedto
import importantedto.concreteedto.cameedto.Absenceedto.Companion.setAudioType
import importantedto.concreteedto.cameedto.Absenceedto.Companion.setType
import importantedto.concreteedto.cameedto.Changingedto
import importantedto.concreteedto.cameedto.Hateedto.SCAN_AUDIOS
import importantedto.concreteedto.cameedto.Hateedto.SCAN_DOCUMENTS
import importantedto.concreteedto.cameedto.Hateedto.SCAN_PHOTOS
import importantedto.concreteedto.cameedto.Hateedto.SCAN_VIDEOS
import importantedto.deserveedto.manufactureredto.viableedto.Earnedto
import importantedto.gallonedto.Buttocksedto
import importantedto.gallonedto.Transcendedto
import importantedto.gallonedto.Tumbleedto
import importantedto.maidedto.witnessedto.nationalismedto.Photocopyedto.showExitFunctionDialog
import importantedto.maidedto.witnessedto.nationalismedto.Photocopyedto.showGerPermission
import importantedto.maidedto.witnessedto.nationalismedto.Salvationedto
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.channels.BufferOverflow
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.launch
import java.io.File

class Spilledto : Murderedto<BiggeredtoBinding>() {

    private val TAG = "FileScanResultActivity"
    private var scanOnce: Boolean = false
    private var scanType = 0
    override val binding: BiggeredtoBinding by lazy {
        BiggeredtoBinding.inflate(layoutInflater)
    }

    private lateinit var fileFolderAdapter: Earnedto


    @SuppressLint("SetTextI18n")
    override fun initView() {
        Transcendedto.setStatusBarLightMode(this, true)
        Transcendedto.setStatusBarColor(this, Color.TRANSPARENT)

        scanType = intent.extras?.getInt("ScanType") ?: 0

        Tumbleedto.logDebug(TAG, "scanType=$scanType")
        when (scanType) {
            SCAN_PHOTOS -> {
                binding.meetingedto.text = "Photo Recovery"
                binding.inventededto.text = "Photos"
            }

            SCAN_DOCUMENTS -> {
                binding.meetingedto.text = "Document Recovery"
                binding.inventededto.text = "Documents"
            }

            SCAN_VIDEOS -> {
                binding.meetingedto.text = "Video Recovery"
                binding.inventededto.text = "videos"
            }
            SCAN_AUDIOS -> {
                binding.meetingedto.text = "Audio Recovery"
                binding.inventededto.text = "Audios"
            }
        }
        fileFolderAdapter = Earnedto(scanType) { folderBean ->
            Flingedto.folderBean = null
            Flingedto.folderBean = folderBean
            startActivity(Intent(this, Flingedto::class.java).apply {
                putExtra("ScanType", scanType)
            })
        }
        binding.questedto.adapter = fileFolderAdapter

        if (checkStorePermission()) {
            beginScan()
        } else {
            showGerPermission(
                desc = "In order to scan and recover your lost photos, videos, and documents, we need to access your device storage. This permission is essential for our app to locate and restore your files.",
                deny = { finishToMain() }) {
                requestStorePermission(launcher, result = {
                    if (it) beginScan() else finishToMain()
                })
            }
        }
    }

    override fun initListener() {
        binding.bangedto.setOnClickListener {
            onBackPressedDispatcher.onBackPressed()
        }
        onBackPressedDispatcher.addCallback {
            showExitFunctionDialog {
                if (it) {
                    Differenceedto.admobMaxShowInterstitialAd(this@Spilledto,false) {
                        finishToMain()
                    }
                } else {
                    finishToMain()
                }
            }
        }
    }


    @SuppressLint("SetTextI18n")
    private fun beginScan() {
        if (scanOnce)
            return

        scanOnce = true
        //变量路径
        val mPathFlow = MutableSharedFlow<String>(
            replay = 5,//当新的订阅者Collect时，发送几个已经发送过的数据给它
            extraBufferCapacity = 5,//减去replay，MutableSharedFlow还缓存多少数据,缓冲池容量 = replay + extraBufferCapacity
            onBufferOverflow = BufferOverflow.DROP_OLDEST//缓存策略，三种 丢掉最新值、丢掉最旧值和挂起
        )
        val pathFlow: SharedFlow<String> = mPathFlow

        //符合条件Flow
        val mFoundFlow = MutableSharedFlow<Pair<Int, String>>(
            replay = 5,
            extraBufferCapacity = 5,
            onBufferOverflow = BufferOverflow.SUSPEND
        )
        val foundFlow: SharedFlow<Pair<Int, String>> = mFoundFlow


        val dialogClass = Salvationedto(this)
        val scanDialog = dialogClass.showFileScanDialog(pathFlow, foundFlow) {

            pathList.add(it)
            binding.becomeedto.text = pathList.size.toString()
            setAdapterData(it)
        }

        val filter = when (scanType) {
            SCAN_PHOTOS -> Buttocksedto::isImage
            SCAN_DOCUMENTS -> Buttocksedto::isDocument
            SCAN_VIDEOS -> Buttocksedto::isVideo
            SCAN_AUDIOS -> Buttocksedto::isAudio
            else -> Buttocksedto::isImage
        }
        val root = Environment.getExternalStorageDirectory()
        lifecycleScope.loadFileByFilter(
            mPathFlow,
            mFoundFlow,
            root, filter = filter,
            onDo = { file ->
                Tumbleedto.logDebug(TAG, "file =${file.absolutePath}")
            },
            onFinish = {
                lifecycleScope.launch(Dispatchers.Main) {
                    binding.hilariousedto.visibility = View.VISIBLE
                    binding.omnipotentedto.text = "Completed"
                    lifecycleScope.launchWhenResumed {
                        Differenceedto.admobMaxShowInterstitialAd(this@Spilledto,false)
                    }
                    binding.graphedto.isVisible = pathList.isEmpty()
                    setAdapterData(null)
                    dialogClass.finishScan {
                        scanDialog.dismiss()
                    }
                }
            }
        )
    }

    private val pathList = ArrayList<String>()
    private val hashMap = HashMap<String, ArrayList<Absenceedto>>()
    private fun setAdapterData(path: String? = null) {
        val flag = path?.let { addMapFolder(it) } ?: true
        if (flag) {
            binding.harmonyedto.text = hashMap.keys.size.toString()
            val mapList = hashMap.map {
                Changingedto(it.key, recoveryList = it.value)
            }
            fileFolderAdapter.setData(mapList)
        }
    }

    private fun addMapFolder(path: String): Boolean {
        var isNewFolder = false
        val folder = File(path).parent?.split("/")?.last() ?: ""
        if (hashMap[folder] == null) {
            hashMap[folder] = arrayListOf()
            isNewFolder = true
        }
        val recoveryBean = Absenceedto(path)
        if (scanType == SCAN_DOCUMENTS) {
            recoveryBean.setType()
        }
        if (scanType == SCAN_AUDIOS) {
            recoveryBean.setAudioType()
        }
        hashMap[folder]?.add(recoveryBean)
        return isNewFolder
    }
}