package rowedto.jockeyedto.sheetedto.atticedto.strainedto.wolfedto.furtheredto

import android.annotation.SuppressLint
import android.content.Intent
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.AccessibleedtoBinding
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.channels.BufferOverflow
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.launch
import rowedto.jockeyedto.sheetedto.balsamedto.formaledto.orientationedto.Patedto.showExitFunctionDialog
import rowedto.jockeyedto.sheetedto.balsamedto.formaledto.orientationedto.Patedto.showGerPermission
import rowedto.jockeyedto.sheetedto.balsamedto.formaledto.orientationedto.Vastedto
import rowedto.jockeyedto.sheetedto.debutedto.revolutionaryedto.Dynamicedto.SCAN_AUDIOS
import rowedto.jockeyedto.sheetedto.debutedto.revolutionaryedto.Dynamicedto.SCAN_DOCUMENTS
import rowedto.jockeyedto.sheetedto.debutedto.revolutionaryedto.Dynamicedto.SCAN_PHOTOS
import rowedto.jockeyedto.sheetedto.debutedto.revolutionaryedto.Dynamicedto.SCAN_VIDEOS
import rowedto.jockeyedto.sheetedto.debutedto.revolutionaryedto.Numberedto
import rowedto.jockeyedto.sheetedto.debutedto.revolutionaryedto.Roomedto
import rowedto.jockeyedto.sheetedto.debutedto.revolutionaryedto.Roomedto.Companion.setAudioType
import rowedto.jockeyedto.sheetedto.debutedto.revolutionaryedto.Roomedto.Companion.setType
import rowedto.jockeyedto.sheetedto.knewedto.economicedto.copyrightedto.Crossingedto
import rowedto.jockeyedto.sheetedto.knewedto.economicedto.copyrightedto.Everythingedto.loadFileByFilter
import rowedto.jockeyedto.sheetedto.knewedto.economicedto.copyrightedto.Studiededto.checkStorePermission
import rowedto.jockeyedto.sheetedto.knewedto.economicedto.copyrightedto.Studiededto.requestStorePermission
import rowedto.jockeyedto.sheetedto.meadowedto.naturaledto.idealedto.Nobodyedto
import rowedto.jockeyedto.sheetedto.raceedto.pavementedto.Dishedto
import rowedto.jockeyedto.sheetedto.raceedto.pavementedto.Spareedto
import rowedto.jockeyedto.sheetedto.raceedto.pavementedto.Stressedto
import rowedto.jockeyedto.sheetedto.strangeedto.pyramidedto.particlesedto.Scandaledto
import java.io.File

class Archiveedto : Crossingedto<AccessibleedtoBinding>() {

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

    private lateinit var fileFolderAdapter: Nobodyedto


    @SuppressLint("SetTextI18n")
    override fun initView() {
        Spareedto.setStatusBarLightMode(this, true)
        //Spareedto.setStatusBarColor(this, Color.TRANSPARENT)
        scanType = intent.extras?.getInt("ScanType") ?: 0

        Dishedto.logDebug(TAG, "scanType=$scanType")
        Scandaledto.admobMaxShowNativeAd(this,binding.tooledto,1)
        when (scanType) {
            SCAN_PHOTOS -> {
                binding.spontaneousedto.text = "Photo Recovery"
                binding.airedto.text = "Photos"
            }

            SCAN_DOCUMENTS -> {
                binding.spontaneousedto.text = "Document Recovery"
                binding.airedto.text = "Documents"
            }

            SCAN_VIDEOS -> {
                binding.spontaneousedto.text = "Video Recovery"
                binding.airedto.text = "videos"
            }
            SCAN_AUDIOS -> {
                binding.spontaneousedto.text = "Audio Recovery"
                binding.airedto.text = "Audios"
            }
        }
        fileFolderAdapter = Nobodyedto(scanType) { folderBean ->
            Attackedto.folderBean = null
            Attackedto.folderBean = folderBean
            startActivity(Intent(this, Attackedto::class.java).apply {
                putExtra("ScanType", scanType)
            })
        }
        binding.funeraledto.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.conditionedto.setOnClickListener {
            onBackPressedDispatcher.onBackPressed()
        }
        onBackPressedDispatcher.addCallback {
            showExitFunctionDialog {
                if (it) {
                    Scandaledto.admobMaxShowInterstitialAd(this@Archiveedto,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 = Vastedto(this)
        val scanDialog = dialogClass.showFileScanDialog(pathFlow, foundFlow) {

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

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

    private val pathList = ArrayList<String>()
    private val hashMap = HashMap<String, ArrayList<Roomedto>>()
    private fun setAdapterData(path: String? = null) {
        val flag = path?.let { addMapFolder(it) } ?: true
        if (flag) {
            binding.huntingedto.text = hashMap.keys.size.toString()
            val mapList = hashMap.map {
                Numberedto(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 = Roomedto(path)
        if (scanType == SCAN_DOCUMENTS) {
            recoveryBean.setType()
        }
        if (scanType == SCAN_AUDIOS) {
            recoveryBean.setAudioType()
        }
        hashMap[folder]?.add(recoveryBean)
        return isNewFolder
    }
}