package com.base.pdfreaderallpdfreader.ui.main.recent

import android.annotation.SuppressLint
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import com.base.pdfreaderallpdfreader.bean.DocumentBean
import com.base.pdfreaderallpdfreader.bean.DocumentBean.Companion.TYPE_PDF
import com.base.pdfreaderallpdfreader.databinding.FragmentRecentBinding
import com.base.pdfreaderallpdfreader.ui.document.DocumentFragment.Companion.jumpOtherDocument
import com.base.pdfreaderallpdfreader.ui.main.DocumentAdapter
import com.base.pdfreaderallpdfreader.ui.pdf.PdfActivity
import com.base.pdfreaderallpdfreader.ui.view.DialogCallBack
import com.base.pdfreaderallpdfreader.ui.view.DocumentDialog.showDocumentHomeMoreDialog
import com.base.pdfreaderallpdfreader.ui.view.PdfDialog.showPdfHomeMoreDialog
import com.base.pdfreaderallpdfreader.utils.LogEx
import com.base.pdfreaderallpdfreader.utils.PdfBoxUtils.checkPdfEncryption
import com.base.pdfreaderallpdfreader.utils.SpStringUtils
import com.base.pdfreaderallpdfreader.utils.SpStringUtils.BOOKMARK_KEY
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.io.File
import kotlin.random.Random


class RecentFragment() : Fragment(), DialogCallBack {

    private val TAG = "RecentFragment"

    private var _binding: FragmentRecentBinding? = null

    private val binding get() = _binding!!
    private lateinit var recentViewModel: RecentViewModel
    private var adapter: DocumentAdapter? = null

    var i = Random(100).nextInt()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        LogEx.logDebug(TAG, "onCreate $i")
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        recentViewModel = ViewModelProvider(this)[RecentViewModel::class.java]
        _binding = FragmentRecentBinding.inflate(inflater, container, false)
        val root: View = binding.root
        return root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        adapter = DocumentAdapter(requireActivity())
        adapter?.itemClickAction = { item: DocumentBean ->
            if (item.type == TYPE_PDF) {
                PdfActivity.jumpPdfActivity(requireActivity(), item)
            } else {
                requireActivity().jumpOtherDocument(item)
            }
        }
        adapter?.moreAction = { item: DocumentBean ->
            if (item.type == TYPE_PDF) {
                requireActivity().showPdfHomeMoreDialog(item, this)
            } else {
                requireContext().showDocumentHomeMoreDialog(item, this)
            }
        }
        binding.rv.adapter = adapter
    }

    @SuppressLint("NotifyDataSetChanged")
    override fun changeBookmark(path: String, isBookmarked: Boolean) {
        if (isBookmarked) {
            SpStringUtils.addSpString(BOOKMARK_KEY, path)
        } else {
            SpStringUtils.deleteSpString(BOOKMARK_KEY, path)
        }
        adapter?.items?.find { it.path == path }?.isBookmarked = isBookmarked
        adapter?.notifyDataSetChanged()
    }

    override fun deleteDocument(item: DocumentBean) {
        val flag = File(item.path).delete()
        if (flag) {
            adapter?.remove(item)
        }
    }

    @SuppressLint("NotifyDataSetChanged")
    override fun changePdfLock(item: DocumentBean) {
        val pdf = adapter?.items?.find { it.path == item.path }
        pdf?.state = requireContext().checkPdfEncryption(item.path)
        adapter?.notifyDataSetChanged()
    }

    override fun renameDocumentBean(file: File, newName: String) {

        try {
            val newFile = File(file.parentFile, newName)
            val result = file.renameTo(newFile)
            if (result) {
                initData()
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    override fun onResume() {
        super.onResume()
        initData()
    }

    private fun initData() {
        lifecycleScope.launch(Dispatchers.IO) {
            launch(Dispatchers.Main) {
                delay(5000)
                binding.swipeRefreshLayout.isRefreshing = false
            }
            val recentList = recentViewModel.getRecentDocument(requireContext())
            launch(Dispatchers.Main) {
                if (recentList.isEmpty()) {
                    binding.llEmpty.visibility = View.VISIBLE
                    adapter?.submitList(listOf())
                } else {
                    binding.llEmpty.visibility = View.GONE
                    adapter?.submitList(recentList)
                }
                binding.swipeRefreshLayout.isRefreshing = false
            }
        }
    }

    companion object {
        var recentNeedRefresh = true
    }


    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
        LogEx.logDebug(TAG, "onDestroyView $i")
    }

    override fun onDestroy() {
        super.onDestroy()
        LogEx.logDebug(TAG, "onDestroy $i")
    }
}