package com.base.datarecovery.activity

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Color
import android.os.Environment
import android.view.View
import androidx.lifecycle.lifecycleScope
import com.base.datarecovery.R
import com.base.datarecovery.bean.ConstObject
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.showGerPermission
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.channels.BufferOverflow
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch

/**
 * 文件扫描,遍历文件夹的方式进行
 */
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, true)
        BarUtils.setStatusBarColor(this, Color.TRANSPARENT)

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

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

            3 -> {
                binding.tvTittle.text = "Videos Recovery"
                binding.ivIcon.setImageResource(R.mipmap.tu_videos_scan)
            }
        }
    }

    override fun initListener() {
        binding.flFanhui.setOnClickListener {
            finishToMain()
        }
        binding.tvScan.setOnClickListener {
            if (checkStorePermission()) {
                binding.llFile.visibility = View.VISIBLE
                beginScan()
            } else {
                requestPermission()
            }
        }
    }

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

        val filter = when (scanType) {
            ConstObject.SCAN_PHOTOS -> ::isImage
            ConstObject.SCAN_DOCUMENTS -> ::isDocument
            ConstObject.SCAN_VIDEOS -> ::isVideo
            else -> ::isImage
        }
        val root = Environment.getExternalStorageDirectory()
        val pathList = arrayListOf<String>()
        lifecycleScope.loadFileByFilter(
            mutableSharedFlow,
            root, filter = filter,
            onDo = { file ->
                LogEx.logDebug(TAG, "file =${file.absolutePath}")
                pathList.add(file.absolutePath)
            },
            onFinish = {
                startActivity(Intent(this@FileScanActivity, FileScanResultActivity::class.java).apply {
                    putExtra("ScanType", scanType)
                    putExtra("PathList", pathList.toTypedArray())
                })
                finish()
            }
        )
        lifecycleScope.launch(Dispatchers.Main) {
            sharedFlow.collectLatest {
                binding.tvPath.text = it
            }
        }

    }


    private fun requestPermission() {

        showGerPermission(null, deny = { finishToMain() }, allow = {

            requestStorePermission(launcher, jumpAction = {}, result = { flag ->
                if (flag) beginScan()
            })

        })


    }

}