package com.base.pdfreaderallpdfreader.ui.main

import android.content.Context
import android.media.MediaScannerConnection
import android.net.Uri
import android.os.Environment
import com.base.pdfreaderallpdfreader.bean.ConstObject
import com.base.pdfreaderallpdfreader.bean.ConstObject.MIME_TYPE_DOC
import com.base.pdfreaderallpdfreader.bean.ConstObject.MIME_TYPE_DOCX
import com.base.pdfreaderallpdfreader.bean.ConstObject.MIME_TYPE_PDF
import com.base.pdfreaderallpdfreader.bean.ConstObject.MIME_TYPE_PPT
import com.base.pdfreaderallpdfreader.bean.ConstObject.MIME_TYPE_PPTX
import com.base.pdfreaderallpdfreader.bean.ConstObject.MIME_TYPE_XLS
import com.base.pdfreaderallpdfreader.bean.ConstObject.MIME_TYPE_XLSX
import com.base.pdfreaderallpdfreader.bean.DocumentBean
import com.base.pdfreaderallpdfreader.bean.DocumentBean.Companion.TYPE_EXCEL
import com.base.pdfreaderallpdfreader.bean.DocumentBean.Companion.TYPE_PDF
import com.base.pdfreaderallpdfreader.bean.DocumentBean.Companion.TYPE_PPT
import com.base.pdfreaderallpdfreader.bean.DocumentBean.Companion.TYPE_WORD
import com.base.pdfreaderallpdfreader.bean.MediaBean
import com.base.pdfreaderallpdfreader.helper.MyApplication.Companion.context
import com.base.pdfreaderallpdfreader.utils.AssetUtils.readByteArrayFromAsset
import com.base.pdfreaderallpdfreader.utils.PdfBoxUtils.checkPdfEncryption
import com.base.pdfreaderallpdfreader.utils.SpStringUtils
import com.base.pdfreaderallpdfreader.utils.SpStringUtils.BOOKMARK_KEY
import com.base.pdfreaderallpdfreader.utils.getMediaFile
import java.io.File
import java.io.FileOutputStream
import java.io.IOException

fun Context.upDateDemoStore() {
    val demoFile = File(filesDir, "demo")
    MediaScannerConnection.scanFile(
        this, arrayOf(demoFile.absolutePath), null
    ) { path: String?, uri: Uri? -> }
}

fun getDocumentAppDir(): File {
    val appDir = File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS), context.packageName)
    if (!appDir.exists())
        appDir.exists()
    return appDir
}

fun Context.saveAssetsFile() {
    val demoFile = File(filesDir, "demo")
    demoFile.mkdirs()
    arrayOf(
        "DEMO.pdf",
        "DEMO.docx",
        "DEMO.xlsx",
        "DEMO.pptx"
    ).forEach {

        val file = File(demoFile, it)
        if (file.exists() && file.length() != 0L) {
            return
        }
        file.createNewFile()

        try {
            FileOutputStream(file).use { fos -> fos.write(readByteArrayFromAsset(it)) }
        } catch (e: IOException) {
            e.printStackTrace()
        }

    }
}

fun getPdfDemo(context: Context): DocumentBean {
    val demoDocumentBean = DocumentBean()
    demoDocumentBean.type = TYPE_PDF
    val demoFile = File(context.filesDir, "demo")
    demoDocumentBean.path = demoFile.listFiles()?.find { it.name.contains(".pdf") }?.absolutePath ?: ""
    context.pdfCheck(demoDocumentBean)
    return demoDocumentBean
}

fun getWordDemo(context: Context): DocumentBean {
    val demoDocumentBean = DocumentBean()
    demoDocumentBean.type = TYPE_WORD
    val demoFile = File(context.filesDir, "demo")
    demoDocumentBean.path = demoFile.listFiles()?.find { it.name.contains(".docx") }?.absolutePath ?: ""
    return demoDocumentBean
}

fun getExcelDemo(context: Context): DocumentBean {
    val demoDocumentBean = DocumentBean()
    demoDocumentBean.type = TYPE_EXCEL
    val demoFile = File(context.filesDir, "demo")
    demoDocumentBean.path = demoFile.listFiles()?.find { it.name.contains(".xlsx") }?.absolutePath ?: ""
    return demoDocumentBean
}

fun getPPtDemo(context: Context): DocumentBean {
    val demoDocumentBean = DocumentBean()
    demoDocumentBean.type = TYPE_PPT
    val demoFile = File(context.filesDir, "demo")
    demoDocumentBean.path = demoFile.listFiles()?.find { it.name.contains(".pptx") }?.absolutePath ?: ""
    return demoDocumentBean
}

fun getAllDocument(context: Context): MutableList<DocumentBean> {
    context.upDateDemoStore()
    if (!ConstObject.haveSaveDemo) {
        context.saveAssetsFile()
        ConstObject.haveSaveDemo = true
    }


    val selectionArgs = arrayOf(
        MIME_TYPE_PDF,
        MIME_TYPE_DOC,
        MIME_TYPE_DOCX,
        MIME_TYPE_XLS,
        MIME_TYPE_XLSX,
        MIME_TYPE_PPT,
        MIME_TYPE_PPTX,
    )

    val list = context.getMediaFile(selectionArgs = selectionArgs)
    val documentList = list.map {
        val documentBean = DocumentBean(it.path, uri = it.uri, type = getDocumentType(it))
        if (documentBean.type == TYPE_PDF) {
            context.pdfCheck(documentBean)
        }
        documentBean
    }
    val new = documentList.toMutableList()
    val pptDemo = getPPtDemo(context)
    if (File(pptDemo.path).exists()) {
        new.add(0, pptDemo)
    }
    val excelDemo = getExcelDemo(context)
    if (File(excelDemo.path).exists()) {
        new.add(0, excelDemo)
    }
    val wordDemp = getWordDemo(context)
    if (File(wordDemp.path).exists()) {
        new.add(0, wordDemp)
    }
    val pdfDemo = getPdfDemo(context)
    if (File(pdfDemo.path).exists()) {
        new.add(0, pdfDemo)
    }
    return new
}

fun getPdfFastSize(context: Context): Int {
    val selectionArgs = arrayOf(
        MIME_TYPE_PDF
    )
    val list = context.getMediaFile(selectionArgs = selectionArgs)
    var size = list.size
    val pdfDemo = getPdfDemo(context)
    if (File(pdfDemo.path).exists()) {
        size += 1
    }
    return size
}

fun getPdfDocument(context: Context): MutableList<DocumentBean> {
    if (!ConstObject.haveSaveDemo) {
        context.saveAssetsFile()
        ConstObject.haveSaveDemo = true
    }
    val selectionArgs = arrayOf(
        MIME_TYPE_PDF
    )
    val list = context.getMediaFile(selectionArgs = selectionArgs)
    val documentList = list.map {
        val demoDocumentBean = DocumentBean(it.path, uri = it.uri, type = TYPE_PDF)
        context.pdfCheck(demoDocumentBean)
        demoDocumentBean
    }
    val new = documentList.toMutableList()
    val pdfDemo = getPdfDemo(context)
    if (File(pdfDemo.path).exists()) {
        new.add(0, pdfDemo)
    }
    return new
}

fun getWordDocument(context: Context): MutableList<DocumentBean> {
    if (!ConstObject.haveSaveDemo) {
        context.saveAssetsFile()
        ConstObject.haveSaveDemo = true
    }
    val selectionArgs = arrayOf(
        MIME_TYPE_DOC,
        MIME_TYPE_DOCX,
    )
    val list = context.getMediaFile(selectionArgs = selectionArgs)
    val documentList = list.map {
        DocumentBean(it.path, uri = it.uri, type = TYPE_WORD)
    }
    val new = documentList.toMutableList()
    val wordDemo = getWordDemo(context)
    if (File(wordDemo.path).exists()) {
        new.add(0, wordDemo)
    }
    return new
}

fun getExcelDocument(context: Context): MutableList<DocumentBean> {
    if (!ConstObject.haveSaveDemo) {
        context.saveAssetsFile()
        ConstObject.haveSaveDemo = true
    }
    val selectionArgs = arrayOf(
        MIME_TYPE_XLS,
        MIME_TYPE_XLSX,
    )
    val list = context.getMediaFile(selectionArgs = selectionArgs)
    val documentList = list.map {
        DocumentBean(it.path, uri = it.uri, type = TYPE_EXCEL)
    }
    val new = documentList.toMutableList()
    val excelDemo = getExcelDemo(context)
    if (File(excelDemo.path).exists()) {
        new.add(0, excelDemo)
    }
    return new
}

fun getPptDocument(context: Context): MutableList<DocumentBean> {
    if (!ConstObject.haveSaveDemo) {
        context.saveAssetsFile()
        ConstObject.haveSaveDemo = true
    }
    val selectionArgs = arrayOf(
        MIME_TYPE_PPT,
        MIME_TYPE_PPTX,
    )
    val list = context.getMediaFile(selectionArgs = selectionArgs)
    val documentList = list.map {
        DocumentBean(it.path, uri = it.uri, type = TYPE_PPT)
    }
    val new = documentList.toMutableList()
    val pptDemo = getPPtDemo(context)
    if (File(pptDemo.path).exists()) {
        new.add(0, pptDemo)
    }
    return new
}


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()
        documentBean.lastViewTime = max
    }
}

fun Context.pdfCheck(pdfDocumentBean: DocumentBean) {
    pdfDocumentBean.state = this.checkPdfEncryption(pdfDocumentBean.path)
}

fun getDocumentType(mediaBean: MediaBean): String {
    return if (mediaBean.path.endsWith(".pdf")) {
        TYPE_PDF
    } else if (mediaBean.path.endsWith(".doc") || mediaBean.path.endsWith(".docx")) {
        TYPE_WORD
    } else if (mediaBean.path.endsWith(".xls") || mediaBean.path.endsWith(".xlsx")) {
        TYPE_EXCEL
    } else if (mediaBean.path.endsWith(".ppt") || mediaBean.path.endsWith(".pptx")) {
        TYPE_PPT
    } else {
        TYPE_PDF
    }
}

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