package com.base.datarecovery.activity.recovery

import android.annotation.SuppressLint
import android.graphics.Color
import android.os.Environment
import androidx.activity.addCallback
import androidx.lifecycle.lifecycleScope
import com.base.datarecovery.R
import com.base.datarecovery.ads.AdmobInterstitialUtils
import com.base.datarecovery.bean.ConstObject.SCAN_DOCUMENTS
import com.base.datarecovery.bean.ConstObject.SCAN_PHOTOS
import com.base.datarecovery.bean.ConstObject.SCAN_VIDEOS
import com.base.datarecovery.databinding.ActivityFileScanBinding
import com.base.datarecovery.help.BaseActivity
import com.base.datarecovery.help.FileHelp.loadFileByFilter
import com.base.datarecovery.help.PermissionHelp.checkStorePermission
import com.base.datarecovery.help.PermissionHelp.requestStorePermission
import com.base.datarecovery.utils.BarUtils
import com.base.datarecovery.utils.FileHexEx.isDocument
import com.base.datarecovery.utils.FileHexEx.isImage
import com.base.datarecovery.utils.FileHexEx.isVideo
import com.base.datarecovery.utils.LogEx
import com.base.datarecovery.view.DialogViews.showExitFunctionDialog
import com.base.datarecovery.view.DialogViews.showGerPermission
import com.base.datarecovery.view.FileScanDialog
import kotlinx.coroutines.channels.BufferOverflow
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.SharedFlow

/**
 * 文件扫描,遍历文件夹的方式进行
 */
class FileScanActivity : BaseActivity<ActivityFileScanBinding>() {

    private val TAG = "FileScanActivity"
    private var scanOnce: Boolean = false

    private var scanType = 0
    override val binding: ActivityFileScanBinding by lazy {
        ActivityFileScanBinding.inflate(layoutInflater)
    }

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

        scanType = intent.extras?.getInt("Type") ?: 0
        when (scanType) {
            SCAN_PHOTOS -> {
                binding.tvTittle.text = "Photos Recovery"
                binding.ivIcon.setImageResource(R.mipmap.tu_photos_scan)
            }

            SCAN_DOCUMENTS -> {
                binding.tvTittle.text = "Documents Recovery"
                binding.ivIcon.setImageResource(R.mipmap.tu_documents_scan)
            }

            SCAN_VIDEOS -> {
                binding.tvTittle.text = "Videos Recovery"
                binding.ivIcon.setImageResource(R.mipmap.tu_videos_scan)
            }
        }
        if (checkStorePermission()) {
            beginScan()
        } else {
            requestPermission()
        }
    }

    override fun initListener() {
        onBackPressedDispatcher.addCallback {
            showExitFunctionDialog {
                AdmobInterstitialUtils.showInterstitialAd(this@FileScanActivity) {
                    finishToMain()
                }
            }
        }
        binding.flFanhui.setOnClickListener {
            onBackPressedDispatcher.onBackPressed()
        }
    }

    @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.SUSPEND//缓存策略，三种 丢掉最新值、丢掉最旧值和挂起
        )
        val pathFlow: SharedFlow<String> = mPathFlow

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

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

        val filter = when (scanType) {
            SCAN_PHOTOS -> ::isImage
            SCAN_DOCUMENTS -> ::isDocument
            SCAN_VIDEOS -> ::isVideo
            else -> ::isImage
        }
        val root = Environment.getExternalStorageDirectory()
        val pathList = arrayListOf<String>()
        lifecycleScope.loadFileByFilter(
            mPathFlow,
            mFoundFlow,
            root, filter = filter,
            onDo = { file ->
                LogEx.logDebug(TAG, "file =${file.absolutePath}")
                pathList.add(file.absolutePath)
            },
            onFinish = {
                if (pathList.isEmpty()) {
                    scanDialog.dismiss()
                    binding.tvBtn.text = "Finish"
                    binding.tvBtn.setOnClickListener {
                        onBackPressedDispatcher.onBackPressed()
                    }
                } else {
                    binding.ivIcon.setImageResource(R.mipmap.queshengye)
                    dialogClass.stopScan(scanType, pathList)
                }

            }
        )


    }


    private fun requestPermission() {

        showGerPermission(tittle = "Storage Permission Required",
            desc = "This feature requires access to your storage to scan your photos, videos, and documents and recover any accidentally deleted data. 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, jumpAction = {}, result = { flag ->
                    if (flag) beginScan()
                })

            })


    }

}