package com.base.pdfreader2.ui.main

import android.content.Context
import com.base.pdfreader2.bean.ConstObject
import com.base.pdfreader2.bean.ConstObject.UI_SORT_FINAL_MODIFIED
import com.base.pdfreader2.bean.ConstObject.UI_SORT_NAME_A_Z
import com.base.pdfreader2.bean.ConstObject.UI_SORT_NAME_Z_A
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.ui.view.DialogView.SortMode
import com.base.pdfreader2.utils.AssetUtils.saveAssetsFile
import com.base.pdfreader2.utils.KotlinExt.toFormatTime3
import com.base.pdfreader2.utils.LogEx
import com.base.pdfreader2.utils.PdfBoxUtils.checkPdfEncryption
import com.base.pdfreader2.utils.SpStringUtils
import com.base.pdfreader2.utils.SpStringUtils.BOOKMARK_KEY
import com.base.pdfreader2.utils.SpStringUtils.LAST_VIEW_KEY
import com.base.pdfreader2.utils.getMediaFile
import com.base.pdfreader2.utils.upDateDemoStore
import java.io.File

class DocumentPresenter(
    val context: Context,
) {

    private val TAG = "DocumentPresenter"

    /**
     * 获取所有的
     */
    fun getAllDocument(type: String): MutableList<DocumentBean> {
        context.upDateDemoStore()
        if (!ConstObject.haveSaveDemo) {
            context.saveAssetsFile()
            ConstObject.haveSaveDemo = true
        }

        when (type) {
            TYPE_PDF -> {
                return getPdfData()
            }

            TYPE_WORD -> {
                return getWordData()
            }

            TYPE_EXCEL -> {
                return getExcelData()
            }

            TYPE_PPT -> {
                return getPptData()
            }

        }
        return mutableListOf()
    }

    /**
     * 获取最近的
     */
    fun getRecentDocument(type: String): List<DocumentBean> {
        val recentList = SpStringUtils.getSpStringList(LAST_VIEW_KEY)
        val list = getAllDocument(type)
        list.forEach { recentFilter(recentList, it) }
        return list.filter { it.lastViewTime != 0L }.sortedByDescending { it.lastViewTime }
    }

    private fun recentFilter(recentList: List<String>, documentBean: DocumentBean) {

        val findLastTime = recentList.filter { it.contains(documentBean.path) }.map {
            it.split("_/_")[1].toLong()
        }
        if (findLastTime.isNotEmpty()) {
            val max = findLastTime.max()
            LogEx.logDebug(TAG, "recentFilter ${documentBean.path} ${max.toFormatTime3()}")
            documentBean.lastViewTime = max
        }
    }

    /**
     * 获取标签的
     */
    fun getBookmarkDocument(type: String): List<DocumentBean> {
        val list = getAllDocument(type)
        return list.filter { it.isBookmarked }
    }

    private fun getPdfData(): MutableList<DocumentBean> {
        val demoDocumentBean = DocumentBean()
        demoDocumentBean.type = TYPE_PDF
        val demoFile = File(context.filesDir, "demo")

        val selectionArgs = arrayOf(ConstObject.MIME_TYPE_PDF)
        demoDocumentBean.path = demoFile.listFiles()?.find { it.name.contains(".pdf") }?.absolutePath ?: ""


        val list = context.getMediaFile(selectionArgs = selectionArgs)
        val documentList = list.map {
            DocumentBean(it.path, uri = it.uri, type = TYPE_PDF)
        }
        val new = documentList.toMutableList()
        if (File(demoDocumentBean.path).exists()) {
            new.add(0, demoDocumentBean)
        }
        val bookmarkList = SpStringUtils.getSpStringList(BOOKMARK_KEY)
        new.map {
            it.state = context.checkPdfEncryption(it.path)
            it.isBookmarked = bookmarkList.contains(it.path)
        }
        return new
    }

    private fun getWordData(): MutableList<DocumentBean> {
        val demoDocumentBean = DocumentBean()
        demoDocumentBean.type = TYPE_WORD
        val demoFile = File(context.filesDir, "demo")

        val selectionArgs = arrayOf(ConstObject.MIME_TYPE_DOC, ConstObject.MIME_TYPE_DOCX)
        demoDocumentBean.path = demoFile.listFiles()?.find { it.name.contains(".docx") }?.absolutePath ?: ""


        val list = context.getMediaFile(selectionArgs = selectionArgs)
        val documentList = list.map {
            DocumentBean(it.path, uri = it.uri, type = TYPE_WORD)
        }
        val new = documentList.toMutableList()
        if (File(demoDocumentBean.path).exists()) {
            new.add(0, demoDocumentBean)
        }
        val bookmarkList = SpStringUtils.getSpStringList(BOOKMARK_KEY)
        new.map {
            it.isBookmarked = bookmarkList.contains(it.path)
        }
        return new
    }

    private fun getExcelData(): MutableList<DocumentBean> {
        val demoDocumentBean = DocumentBean()
        demoDocumentBean.type = TYPE_EXCEL
        val demoFile = File(context.filesDir, "demo")

        val selectionArgs = arrayOf(ConstObject.MIME_TYPE_XLS, ConstObject.MIME_TYPE_XLSX)
        demoDocumentBean.path = demoFile.listFiles()?.find { it.name.contains(".xlsx") }?.absolutePath ?: ""

        val list = context.getMediaFile(selectionArgs = selectionArgs)
        val documentList = list.map {
            DocumentBean(it.path, uri = it.uri, type = TYPE_EXCEL)
        }
        val new = documentList.toMutableList()
        if (File(demoDocumentBean.path).exists()) {
            new.add(0, demoDocumentBean)
        }
        val bookmarkList = SpStringUtils.getSpStringList(BOOKMARK_KEY)
        new.map {
            it.isBookmarked = bookmarkList.contains(it.path)
        }
        return new
    }

    private fun getPptData(): MutableList<DocumentBean> {
        val demoDocumentBean = DocumentBean()
        demoDocumentBean.type = TYPE_PPT
        val demoFile = File(context.filesDir, "demo")

        val selectionArgs = arrayOf(ConstObject.MIME_TYPE_PPT, ConstObject.MIME_TYPE_PPTX)
        demoDocumentBean.path = demoFile.listFiles()?.find { it.name.contains(".pptx") }?.absolutePath ?: ""


        val list = context.getMediaFile(selectionArgs = selectionArgs)
        val documentList = list.map {
            DocumentBean(it.path, uri = it.uri, type = TYPE_PPT)
        }
        val new = documentList.toMutableList()
        if (File(demoDocumentBean.path).exists()) {
            new.add(0, demoDocumentBean)
        }
        val bookmarkList = SpStringUtils.getSpStringList(BOOKMARK_KEY)
        new.map {
            it.isBookmarked = bookmarkList.contains(it.path)
        }
        return new
    }

    fun sortByMode(list: List<DocumentBean>): List<DocumentBean> {
        when (SortMode) {
            ConstObject.UI_SORT_LAST_MODIFIED -> {
                return list.sortedByDescending { File(it.path).lastModified() }
            }

            UI_SORT_FINAL_MODIFIED -> {
                return list.sortedBy { File(it.path).lastModified() }
            }

            UI_SORT_NAME_A_Z -> {
                return list.sortedBy { File(it.path).name }
            }
            UI_SORT_NAME_Z_A -> {
                return list.sortedByDescending { File(it.path).name }
            }

        }
        return list
    }

}