package rallyedto.finishedto.biggestedto.canedto.greenedto

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.QuarreledtoBinding
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.channels.BufferOverflow
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.launch
import rallyedto.battleedto.acresedto.Circulationedto.loadFileByFilter
import rallyedto.battleedto.acresedto.Lemonedto
import rallyedto.battleedto.acresedto.Napedto.checkStorePermission
import rallyedto.battleedto.acresedto.Napedto.requestStorePermission
import rallyedto.dumpedto.editionedto.Assetedto
import rallyedto.farewelledto.Lazyedto
import rallyedto.farewelledto.Technologyedto.showExitFunctionDialog
import rallyedto.farewelledto.Technologyedto.showGerPermission
import rallyedto.policeedto.huntedto.Desertedto
import rallyedto.policeedto.huntedto.Desertedto.Companion.setAudioType
import rallyedto.policeedto.huntedto.Desertedto.Companion.setType
import rallyedto.policeedto.huntedto.Mediumedto
import rallyedto.policeedto.huntedto.Snuggleedto.SCAN_AUDIOS
import rallyedto.policeedto.huntedto.Snuggleedto.SCAN_DOCUMENTS
import rallyedto.policeedto.huntedto.Snuggleedto.SCAN_PHOTOS
import rallyedto.policeedto.huntedto.Snuggleedto.SCAN_VIDEOS
import rallyedto.sunedto.tumouredto.majorityedto.loseedto.Togetheredto
import rallyedto.talledto.blewedto.Islandedto
import rallyedto.talledto.blewedto.Leafletedto
import rallyedto.talledto.blewedto.Musicaledto
import java.io.File

class Snailedto : Lemonedto<QuarreledtoBinding>() {

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

    private lateinit var fileFolderAdapter: Assetedto


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

        Musicaledto.logDebug(TAG, "scanType=$scanType")
        Togetheredto.showNativeAd(this,binding.jeweledto)
        when (scanType) {
            SCAN_PHOTOS -> {
                binding.loveredto.text = "Photo Recovery"
                binding.deputyedto.text = "Photos"
            }

            SCAN_DOCUMENTS -> {
                binding.loveredto.text = "Document Recovery"
                binding.deputyedto.text = "Documents"
            }

            SCAN_VIDEOS -> {
                binding.loveredto.text = "Video Recovery"
                binding.deputyedto.text = "videos"
            }
            SCAN_AUDIOS -> {
                binding.loveredto.text = "Audio Recovery"
                binding.deputyedto.text = "Audios"
            }
        }
        fileFolderAdapter = Assetedto(scanType) { folderBean ->
            Dragonedto.folderBean = null
            Dragonedto.folderBean = folderBean
            startActivity(Intent(this, Dragonedto::class.java).apply {
                putExtra("ScanType", scanType)
            })
        }
        binding.autonomyedto.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.unfortunateedto.setOnClickListener {
            onBackPressedDispatcher.onBackPressed()
        }
        onBackPressedDispatcher.addCallback {
            showExitFunctionDialog {
                admobMaxShowInterstitialAd(isShow = Togetheredto.isShowAdBackInter()) {
                    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 = Lazyedto(this)
        val scanDialog = dialogClass.showFileScanDialog(pathFlow, foundFlow) {

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

        val filter = when (scanType) {
            SCAN_PHOTOS -> Leafletedto::isImage
            SCAN_DOCUMENTS -> Leafletedto::isDocument
            SCAN_VIDEOS -> Leafletedto::isVideo
            SCAN_AUDIOS -> Leafletedto::isAudio
            else -> Leafletedto::isImage
        }
        val root = Environment.getExternalStorageDirectory()
        lifecycleScope.loadFileByFilter(
            mPathFlow,
            mFoundFlow,
            root, filter = filter,
            onDo = { file ->
                Musicaledto.logDebug(TAG, "file =${file.absolutePath}")
            },
            onFinish = {
                lifecycleScope.launch(Dispatchers.Main) {
                    binding.objectiveedto.visibility = View.VISIBLE
                    binding.chamberedto.text = "Completed"
                    lifecycleScope.launchWhenResumed {
                        admobMaxShowInterstitialAd{}
                    }
                    binding.justifyedto.isVisible = pathList.isEmpty()
                    setAdapterData(null)
                    dialogClass.finishScan {
                        scanDialog.dismiss()
                    }
                }
            }
        )
    }

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