package com.base.pdfviewerscannerwhite.ui.main

import android.content.Context
import androidx.lifecycle.LifecycleCoroutineScope
import com.base.pdfviewerscannerwhite.bean.ConstObject
import com.base.pdfviewerscannerwhite.bean.ConstObject.haveSaveDemo
import com.base.pdfviewerscannerwhite.bean.DocumentBean
import com.base.pdfviewerscannerwhite.ui.document.pdf.PdfBoxUtils
import com.base.pdfviewerscannerwhite.utils.AssetUtils.saveAssetsFile
import com.base.pdfviewerscannerwhite.utils.LogEx
import com.base.pdfviewerscannerwhite.utils.SpStringUtils
import com.base.pdfviewerscannerwhite.utils.getMediaFile
import com.base.pdfviewerscannerwhite.utils.upDateDemoStore
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.io.File

class DocumentPresenter(
    val context: Context,
    val documentView: DocumentView,
    val type: String,
    val lifecycleScope: LifecycleCoroutineScope
) {
    private val TAG = "DocumentPresenter"

    private fun getDocumentBeanList(): List<DocumentBean> {
        LogEx.logDebug(TAG, "getDocumentBeanList")
        context.upDateDemoStore()
        if (!haveSaveDemo) {
            context.saveAssetsFile()
            haveSaveDemo = true
        }

        var selectionArgs = arrayOf(ConstObject.MIME_TYPE_PDF)
        val demoDocumentBean = DocumentBean()
        val demoFile = File(context.filesDir, "demo")

        if (type == DocumentBean.TYPE_PDF) {
            selectionArgs = arrayOf(ConstObject.MIME_TYPE_PDF)
            demoDocumentBean.path = demoFile.listFiles()?.find { it.name.contains(".pdf") }?.absolutePath ?: ""
        }
        if (type == DocumentBean.TYPE_WORD) {
            selectionArgs = arrayOf(ConstObject.MIME_TYPE_DOC, ConstObject.MIME_TYPE_DOCX)
            demoDocumentBean.path = demoFile.listFiles()?.find { it.name.contains(".docx") }?.absolutePath ?: ""
        }
        if (type == DocumentBean.TYPE_EXCEL) {
            selectionArgs = arrayOf(ConstObject.MIME_TYPE_XLS, ConstObject.MIME_TYPE_XLSX)
            demoDocumentBean.path = demoFile.listFiles()?.find { it.name.contains(".xlsx") }?.absolutePath ?: ""
        }
        if (type == DocumentBean.TYPE_PPT) {
            selectionArgs = arrayOf(ConstObject.MIME_TYPE_PPT, ConstObject.MIME_TYPE_PPTX)
            demoDocumentBean.path = demoFile.listFiles()?.find { it.name.contains(".pptx") }?.absolutePath ?: ""
        }
        demoDocumentBean.type = type

        val bookmarkList = SpStringUtils.getSpStringList(SpStringUtils.BOOKMARK_KEY)

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

    fun initData() = lifecycleScope.launch(Dispatchers.IO) {
        val documentList = getDocumentBeanList()

        launch(Dispatchers.Main) {
            documentView.refreshDocumentRv(documentList)
        }

    }

    fun initUnLockData() = lifecycleScope.launch(Dispatchers.IO) {
        val documentList = getDocumentBeanList()
        documentList.forEach {
            it.state = PdfBoxUtils.checkPdfEncryption(it.path)
        }
        val list = documentList.filter { it.state == 0 }
        launch(Dispatchers.Main) {
            documentView.refreshDocumentRv(list)
        }
    }

    fun initLoadData() = lifecycleScope.launch(Dispatchers.IO) {
        val documentList = getDocumentBeanList()
        documentList.forEach {
            it.state = PdfBoxUtils.checkPdfEncryption(it.path)
        }
        val list = documentList.filter { it.state == 1 }
        launch(Dispatchers.Main) {
            documentView.refreshDocumentRv(list)
        }
    }


    fun saveBookmarkChange(addRemove: Boolean, path: String) {
        if (addRemove) {
            SpStringUtils.addSpString(SpStringUtils.BOOKMARK_KEY, path)
        } else {
            SpStringUtils.deleteSpString(SpStringUtils.BOOKMARK_KEY, path)
        }
    }

    fun renameDocumentBean(
        file: File, newName: String,
        callBack: ((newPath: String) -> Unit)? = null
    ) = lifecycleScope.launch(Dispatchers.IO) {

        var newPath = ""
        try {
            val nameFile = File(file.parentFile, newName)
            val result = file.renameTo(nameFile)
            if (result) {
                newPath = nameFile.absolutePath
            }
        } catch (e: Exception) {

        }
        launch(Dispatchers.Main) {
            callBack?.invoke(newPath)
        }
    }

    fun deleteDocumentBean(item: DocumentBean) {
        runCatching {
            val file = File(item.path)
            file.delete()
        }
    }


}