package com.isidroid.utils

import android.content.Context
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.pdf.PdfRenderer
import android.net.Uri
import android.os.ParcelFileDescriptor
import timber.log.Timber
import java.io.File

fun Uri.savePdfAsBitmapFiles(context: Context): List<File>? {
    val descriptor = context.contentResolver.openFileDescriptor(this, "r") ?: return null
    return descriptor.toBitmapList()
}

fun File.savePdfAsBitmapFiles(): List<File> {
    Timber.i("==> file=$absolutePath, length=${length()}")

    val descriptor = ParcelFileDescriptor.open(this, ParcelFileDescriptor.MODE_READ_ONLY)
    return descriptor.toBitmapList()
}

private fun ParcelFileDescriptor.toBitmapList(): List<File> {
    val renderer = PdfRenderer(this)

    val result = (0 until renderer.pageCount).mapNotNull { pageNumber ->
        val page = renderer.openPage(pageNumber)
        try {
            val bitmap = Bitmap.createBitmap(page.width, page.height, Bitmap.Config.ARGB_8888)
            val canvas = Canvas(bitmap)
            canvas.drawColor(Color.WHITE)

            page.render(bitmap, null, null, PdfRenderer.Page.RENDER_MODE_FOR_PRINT)
            bitmap.saveToTempFile()
        } catch (t: Throwable) {
            Timber.e(t)
            null
        } finally {
            page.close()
        }
    }

    close()
    renderer.close()

    return result
}