package com.base.filerecoveryrecyclebin.fragment

import android.app.Dialog
import android.content.Intent
import android.os.Build
import android.os.Handler
import androidx.annotation.RequiresApi
import androidx.core.view.isVisible
import androidx.lifecycle.lifecycleScope
import com.base.filerecoveryrecyclebin.activity.MainActivity
import com.base.filerecoveryrecyclebin.activity.recyclebin.RecycleBinDetailActivity
import com.base.filerecoveryrecyclebin.adapter.RecycleBinAdapter
import com.base.filerecoveryrecyclebin.ads.AdmobMaxHelper
import com.base.filerecoveryrecyclebin.bean.RecycleBinBean
import com.base.filerecoveryrecyclebin.bean.RecycleBinBean.Companion.mAudioStr
import com.base.filerecoveryrecyclebin.bean.RecycleBinBean.Companion.mDocumentStr
import com.base.filerecoveryrecyclebin.bean.RecycleBinBean.Companion.mImageStr
import com.base.filerecoveryrecyclebin.bean.RecycleBinBean.Companion.mVideoStr
import com.base.filerecoveryrecyclebin.databinding.FragmentRecycleBinBinding
import com.base.filerecoveryrecyclebin.help.BaseFragment
import com.base.filerecoveryrecyclebin.help.PermissionHelp.checkStorePermission
import com.base.filerecoveryrecyclebin.help.PermissionHelp.requestStorePermission
import com.base.filerecoveryrecyclebin.service.BackUpUtils
import com.base.filerecoveryrecyclebin.utils.LogEx
import com.base.filerecoveryrecyclebin.view.DialogViews.showGerPermission
import com.base.filerecoveryrecyclebin.view.DialogViews.showRecycleBinFilter
import com.google.gson.Gson
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

class RecycleBinFragment : BaseFragment<FragmentRecycleBinBinding>() {

    private val TAG = "RecycleBinFragment"
    private lateinit var handler: Handler
    private lateinit var recycleBinAdapter: RecycleBinAdapter

    override val binding: FragmentRecycleBinBinding by lazy {
        FragmentRecycleBinBinding.inflate(layoutInflater)
    }

    @RequiresApi(Build.VERSION_CODES.Q)
    override fun setView() {

        recycleBinAdapter = RecycleBinAdapter { bean ->
            startActivity(Intent(requireContext(), RecycleBinDetailActivity::class.java).apply {
                putExtra("Json", Gson().toJson(bean))
            })
        }
        binding.rv.adapter = recycleBinAdapter
        AdmobMaxHelper.admobMaxShowNativeAd(requireActivity(),binding.idFlNative,1)

    }

    var binFilter: String? = null

    @RequiresApi(Build.VERSION_CODES.Q)
    override fun setListener() {
        super.setListener()
        binding.flGengduo.setOnClickListener {
            requireContext().showRecycleBinFilter(lifecycleScope, binFilter) {
                binFilter = if (binFilter == it) null else it
                initData()
            }
        }
        binding.swipeRefreshLayout.setOnRefreshListener {
            binding.swipeRefreshLayout.isRefreshing = true
            initData {
                binding.swipeRefreshLayout.isRefreshing = false
            }
        }
    }

    private fun filterAction(bin: RecycleBinBean): Boolean {
        LogEx.logDebug(TAG, "binFilter=$binFilter")
        return when (binFilter) {
            "Photos" -> mImageStr.contains("." + bin.mimeType)
            "Videos" -> mVideoStr.contains("." + bin.mimeType)
            "Audios" -> mAudioStr.contains("." + bin.mimeType)
            "Documents" -> mDocumentStr.contains("." + bin.mimeType)
            else -> true
        }
    }

    private fun initData(callBack: (() -> Unit)? = null) {
        LogEx.logDebug(TAG, "initData")
        lifecycleScope.launch(Dispatchers.IO) {
            val beanList = BackUpUtils.getBackUpListObj()
            val deleteFile: List<RecycleBinBean>? = beanList?.filter { it.deleted && filterAction(it) }
//            val deleteFile: List<RecycleBinBean>? = beanList
            LogEx.logDebug(TAG, "deleteFile=$deleteFile")
            deleteFile?.forEach {
                LogEx.logDebug(TAG, it.toString())
            }
            launch(Dispatchers.Main) {
                callBack?.invoke()
                binding.rv.isVisible = deleteFile?.isNotEmpty() == true
                binding.llEmpty.isVisible = deleteFile.isNullOrEmpty()
                recycleBinAdapter.setData(deleteFile ?: listOf())
            }
        }
    }

    var permissionDialog: Dialog? = null
    override fun onResume() {
        super.onResume()
        LogEx.logDebug(TAG, "onResume")
        if (requireContext().checkStorePermission()) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                initData()
            }
        }
        val launcher = (requireActivity() as MainActivity).launcher
        if (!requireActivity().checkStorePermission() && permissionDialog == null) {
            permissionDialog = requireContext().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 = {
                    permissionDialog = null
                    (requireActivity() as MainActivity).setPage(0)
                },
                allow = {
                    permissionDialog = null
                    requireContext().requestStorePermission(launcher, result = { flag ->
                        if (flag) {
                            initData()
                        }
                    })
                })
        }
    }

    override fun onPause() {
        super.onPause()
        LogEx.logDebug(TAG, "onPause")
    }


}