package com.base.pdfviewerscannerwhite.utils

import android.content.Context
import android.graphics.Bitmap
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.Drawable
import com.tom_roush.pdfbox.pdmodel.PDDocument
import com.tom_roush.pdfbox.rendering.ImageType
import com.tom_roush.pdfbox.rendering.PDFRenderer
import com.tom_roush.pdfbox.rendering.RenderDestination
import java.io.File


object PdfUtils {

    private val TAG = "PdfUtils"

    fun getPdfDrawables(context: Context, filePath: String, scale: Float = 1f): List<Drawable> {
        val drawableList = arrayListOf<Drawable>()
        val document = PDDocument.load(File(filePath))
        try {
            val renderer = PDFRenderer(document)
            for (pageIndex in 0..document.numberOfPages) {
                val startTime = System.currentTimeMillis()
                val bitmap: Bitmap = renderer.renderImage(pageIndex, scale, ImageType.RGB, RenderDestination.EXPORT)
                val byteCount = bitmap.byteCount
                val endTime = System.currentTimeMillis()
                LogEx.logDebug(TAG, "$pageIndex byteCount=$byteCount time=${endTime - startTime}")
                val drawable = BitmapDrawable(context.resources, bitmap)
                drawableList.add(drawable)
            }
        } catch (e: Exception) {
            e.printStackTrace()
        } finally {
            document.close()
        }
        return drawableList
    }

    fun getNumberOfPages(filePath: String): Int {
        val document = PDDocument.load(File(filePath))
        return document.numberOfPages
    }

    fun getPdfDrawablePage(
        context: Context,
        filePath: String,
        pageIndex: Int,
        scale: Float = 1f
    ): Drawable {
        val document = PDDocument.load(File(filePath))
        val renderer = PDFRenderer(document)

        val bitmap: Bitmap = renderer.renderImage(pageIndex, scale, ImageType.RGB, RenderDestination.EXPORT)

        val drawable = BitmapDrawable(context.resources, bitmap)

        return drawable
    }

}