package com.base.pdfviewerscannerwhite.ui.document.pdf

import android.content.Context
import android.os.Handler
import com.base.pdfviewerscannerwhite.bean.PdfPageBean
import com.base.pdfviewerscannerwhite.utils.PdfUtils
import com.tom_roush.pdfbox.pdmodel.PDDocument
import java.io.File


class PdfPresenter(
    val context: Context,
    val pdfView: PdfView? = null
) {

    var handler: Handler? = null

    fun iniPdfPage(filePath: String) {
        val list = arrayListOf<PdfPageBean>()
        val number = PdfUtils.getNumberOfPages(filePath)
        repeat(number) {
            list.add(PdfPageBean(it))
        }
        pdfView?.initPdfPageRv(list)
    }

    fun splitPdf(
        file: File, newName: String, splitIndex: List<Int>,
        finishAction: (newFile: File?) -> Unit
    ) = Thread {
        val newFile = File(file.parentFile, newName)
        try {
            // 加载现有 PDF 文档
            val sourceDocument = PDDocument.load(file)

            // 创建新的 PDF 文档
            val newDocument = PDDocument()

            // 遍历指定的页面范围
            splitIndex.forEach { index ->
                val page = sourceDocument.getPage(index)
                newDocument.addPage(page)
            }
            // 保存新的 PDF 文档
            newDocument.save(newFile)
            newDocument.close()
            sourceDocument.close()
        } catch (e: Exception) {
            println("Error occurred while splitting PDF.")
            finishAction.invoke(null)
            return@Thread
        }
        finishAction.invoke(newFile)
    }.start()
}