package com.base.pdfreader2.ui.main

import android.annotation.SuppressLint
import android.content.Intent
import androidx.core.view.isVisible
import androidx.lifecycle.lifecycleScope
import com.base.pdfreader2.bean.ConstObject
import com.base.pdfreader2.bean.DocumentBean
import com.base.pdfreader2.bean.DocumentBean.Companion.TYPE_EXCEL
import com.base.pdfreader2.bean.DocumentBean.Companion.TYPE_PDF
import com.base.pdfreader2.bean.DocumentBean.Companion.TYPE_PPT
import com.base.pdfreader2.bean.DocumentBean.Companion.TYPE_WORD
import com.base.pdfreader2.databinding.FragmentDocumentBinding
import com.base.pdfreader2.helper.BaseFragment
import com.base.pdfreader2.ui.view.DocumentDialog.showDocumentHomeMoreDialog
import com.base.pdfreader2.ui.view.PdfDialog.showPdfHomeMoreDialog
import com.base.pdfreader2.utils.PdfBoxUtils.checkPdfEncryption
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.io.File
import java.util.Locale


class DocumentFragment() : BaseFragment<FragmentDocumentBinding>() {

    private val TAG = "DocumentFragment"
    private var type = TYPE_PDF

    private lateinit var adapter: DocumentAdapter
    private lateinit var documentPresenter: DocumentPresenter

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

    constructor(type: String) : this() {
        this.type = type
    }

    override fun setView() {
        documentPresenter = DocumentPresenter(requireContext())

        initAdapter()

        binding.swipeRefreshLayout.isRefreshing = true
    }

    private fun initAdapter() {
        adapter = DocumentAdapter()
        adapter.bookmarkAction = { addRemove, path ->
            documentPresenter.saveBookmarkChange(addRemove, path)
        }
        adapter.itemClick = { item ->
//            if (AdmobHelper.isShowOpenDocumentInter()) {
//                AdmobInterstitialUtils.showInterstitialAd(requireActivity()) {
//                    if (it) {
//                        lastOpenDocumentShowAd = System.currentTimeMillis()
//                    }
//                    requireActivity().jumpDocument(item)
//                }
//            } else {
//                requireActivity().jumpDocument(item)
//            }
        }
        adapter.moreAction = { item ->
            documentMoreAction.invoke(item)
        }
        binding.rv.adapter = adapter
    }

     var documentMoreAction: (item: DocumentBean) -> Unit = { item ->
        val mainActivity = (requireActivity() as MainActivity)
        if (item.type == TYPE_PDF) {
            requireContext().showPdfHomeMoreDialog(item, this, documentPresenter)
        }

        if (item.type == TYPE_WORD || item.type == TYPE_EXCEL || item.type == TYPE_PPT) {
            requireContext().showDocumentHomeMoreDialog(item, this, documentPresenter)
        }
    }

    override fun setListener() {
        super.setListener()
        binding.swipeRefreshLayout.setOnRefreshListener {
            binding.swipeRefreshLayout.isRefreshing = true
            refreshData()
        }
    }

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

    fun refreshData() {
        if (isInitialized && !isHidden && isVisible) {
            val mainActivity = (requireActivity() as MainActivity?)
            mainActivity ?: return
            when (mainActivity.dataType) {
                ConstObject.DOCUMENT_DATA_TYPE -> refreshAllData()
                ConstObject.RECENT_DATA_TYPE -> refreshRecentData()
                ConstObject.BOOKMARK_DATA_TYPE -> refreshBookmarkData()
            }
        }
    }

    private fun refreshRecentData() = lifecycleScope.launch(Dispatchers.IO) {
        val list = documentPresenter.getRecentDocument(type)
        launch(Dispatchers.Main) {
            binding.llEmpty.isVisible = list.isEmpty()
            adapter.submitList(list)
            binding.swipeRefreshLayout.isRefreshing = false
        }
    }

    private fun refreshBookmarkData() = lifecycleScope.launch(Dispatchers.IO) {
        val list = documentPresenter.getBookmarkDocument(type)
        lifecycleScope.launch(Dispatchers.Main) {
            binding.llEmpty.isVisible = list.isEmpty()
            binding.swipeRefreshLayout.isRefreshing = false
            adapter.submitList(documentPresenter.sortByMode(list))
        }
    }

    private fun refreshAllData() = lifecycleScope.launch(Dispatchers.IO) {
        val list = documentPresenter.getAllDocument(type)
        launch(Dispatchers.Main) {
            binding.llEmpty.isVisible = list.isEmpty()
            binding.swipeRefreshLayout.isRefreshing = false
            adapter.submitList(documentPresenter.sortByMode(list))
        }
    }

    @SuppressLint("NotifyDataSetChanged")
    fun changeSelectUi(select: Boolean) {
        if (isVisible) {
            adapter.items.forEach {
                if (select) {
                    it.uiType = 1
                    binding.swipeRefreshLayout.isEnabled = false
                } else {
                    it.isSelect = false
                    it.uiType = 0
                    binding.swipeRefreshLayout.isEnabled = true
                }
            }
            adapter.notifyDataSetChanged()
        }
    }

    fun getSearchItems(search: String): List<DocumentBean> {
        if (isVisible) {
            return adapter.items.filter {
                File(it.path).name.lowercase(Locale.ENGLISH).contains(search.lowercase(Locale.ENGLISH))
            }
        }
        return listOf()
    }

    fun splitPdf(path: String, pwd: String?) {
//        startActivity(Intent(requireContext(), PdfSplitActivity::class.java).apply {
//            putExtra("path", path)
//            putExtra("pwd", pwd)
//        })
    }

    fun mergePdf(path: String) {
//        startActivity(Intent(requireContext(), PdfSelectActivity::class.java).apply {
//            putExtra("doWhat", ConstObject.DO_MERGE_PDF)
//        })
    }

    fun removeItem(item: DocumentBean) {
        val list = arrayListOf<DocumentBean>()
        list.addAll(adapter.items)
        list.removeIf { it.path == item.path }
        adapter.submitList(list)
    }

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


}