package com.base.datarecovery.fragment

import android.content.ComponentCallbacks
import android.content.Intent
import android.view.View
import android.widget.Toast
import androidx.lifecycle.lifecycleScope
import com.base.datarecovery.activity.privacyspace.PrivacyImportActivity
import com.base.datarecovery.activity.privacyspace.PrivacyManageActivity
import com.base.datarecovery.activity.privacyspace.PrivacySpaceActivity
import com.base.datarecovery.adapter.FileGridAdapter
import com.base.datarecovery.databinding.FragmentPrivacyPageBinding
import com.base.datarecovery.help.BaseFragment
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.LogEx
import com.base.datarecovery.view.DialogViews.showCameraSettingDialog
import com.base.datarecovery.view.DialogViews.showGerPermission
import com.base.datarecovery.view.DialogViews.showImageImportDialog
import java.io.File
import kotlin.random.Random

class PrivacyPageFragment(
    val mediaType: String
) : BaseFragment<FragmentPrivacyPageBinding>() {

    private val TAG = "PrivacyPageFragment"

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

    private lateinit var adapter: FileGridAdapter

    override fun setView() {
        adapter = FileGridAdapter()
        binding.rv.adapter = adapter

        if (requireContext().checkStorePermission()) {
            initData()
        } else {
            val activity = (requireActivity() as PrivacySpaceActivity)

            requireContext().showGerPermission("Privacy Space Access",
                "To help you protect your privacy, our app needs to scan your device for photos and videos. We will use this information to create a secure private space that only you can access. We do not collect any personal information or data. Please click \"Agree\" to grant us permission to scan your device or \"Cancel\" to exit.",
                denyText = "Exit",
                allowText = "Agree",
                deny = {
                    activity.finishToMain()
                },
                allow = {
                    requireContext().requestStorePermission(activity.launcher, result = {
                        if (it) {
                            initData()
                        } else {
                            activity.finishToMain()
                        }
                    })
                })

        }
    }

    override fun setListener() {
        arrayOf(binding.ivAdd, binding.ivAddEmpty).forEach {
            it.setOnClickListener {
                requireContext().showImageImportDialog(import = {
                    val launcher = (requireActivity() as PrivacySpaceActivity).launcher
                    launcher.launch(
                        Intent(requireContext(), PrivacyImportActivity::class.java)
                    ) { activityResult ->
                        val result = activityResult.data?.extras?.getString("Result")
                        Toast.makeText(requireContext(), result, Toast.LENGTH_SHORT).show()
                        initData()
                    }
                }, camera = {
                    requireContext().showCameraSettingDialog()
                })
            }
        }
        binding.swipeRefreshLayout.setOnRefreshListener {
            binding.swipeRefreshLayout.isRefreshing = true
            initData {
                binding.root.postDelayed({
                    binding.swipeRefreshLayout.isRefreshing = false
                }, Random.nextLong(1500))
            }
        }
        binding.tvManager.setOnClickListener {
            startActivity(Intent(requireContext(), PrivacyManageActivity::class.java).apply {
                putExtra("mediaType", mediaType)
            })
        }

    }


    private fun initData(callback: (() -> Unit)? = null) {
        val dir = if (mediaType == "Photos") {
            File(requireContext().filesDir, "photos")
        } else {
            File(requireContext().filesDir, "videos")
        }
        if (!dir.exists()) {
            dir.mkdirs()
        }
        val list = arrayListOf<String>()

        lifecycleScope.loadFileByFilter(folder = dir,
            filter = { true },
            onDo = {
                LogEx.logDebug(TAG, "$it")
                list.add(it.absolutePath)
            },
            onFinish = {
                if (list.isNotEmpty()) {
                    binding.llEmpty.visibility = View.GONE
                    binding.rv.visibility = View.VISIBLE
                    binding.ivAdd.visibility = View.VISIBLE
                    binding.tvManager.visibility = View.VISIBLE
                }
                adapter.setData(list)
                callback?.invoke()
            })
    }
}