package com.anonymous.Assemblr


import android.graphics.Bitmap
import android.graphics.pdf.PdfRenderer
import android.os.ParcelFileDescriptor
import android.util.Base64
import com.facebook.react.bridge.Promise
import com.facebook.react.bridge.ReactApplicationContext
import com.facebook.react.bridge.ReactContextBaseJavaModule
import com.facebook.react.bridge.ReactMethod
import com.facebook.react.bridge.WritableNativeArray
import java.io.ByteArrayOutputStream
import java.io.File
import java.io.FileOutputStream
import androidx.core.graphics.createBitmap

class PdfToBitmapModule(reactContext: ReactApplicationContext) :
    ReactContextBaseJavaModule(reactContext) {
    override fun getName(): String = "PdfToBitmap"

    @ReactMethod
    fun convertPdfToBitmaps(pdfBase64: String, promise: Promise) {
        try {
            // Decode base64 PDF to byte array
            val pdfBytes = Base64.decode(pdfBase64, Base64.DEFAULT)

            // Create temporary file for PDF
            val tempFile = File.createTempFile("tempPdf", ".pdf", reactApplicationContext.cacheDir)
            FileOutputStream(tempFile).use { fos ->
                fos.write(pdfBytes)
            }

            // Initialize PdfRenderer
            val fd = ParcelFileDescriptor.open(tempFile, ParcelFileDescriptor.MODE_READ_ONLY)
            val pdfRenderer = PdfRenderer(fd)

            // Convert each page to a bitmap
            val bitmapBase64List = WritableNativeArray()
            for (pageIndex in 0 until pdfRenderer.pageCount) {
                val page = pdfRenderer.openPage(pageIndex)
                val scaleFactor = if (page.width < 100) 100 else 5
                val bitmap = createBitmap(page.width * scaleFactor, page.height * scaleFactor)
                page.render(bitmap, null, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY)

                // Convert bitmap to base64
                val stream = ByteArrayOutputStream()
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream)
                val byteArray = stream.toByteArray()
                val base64String = Base64.encodeToString(byteArray, Base64.NO_WRAP)
                bitmapBase64List.pushString(base64String)

                // Clean up
                bitmap.recycle()
                page.close()
            }

            // Clean up renderer and file
            pdfRenderer.close()
            tempFile.delete()

            promise.resolve(bitmapBase64List)
        } catch (e: Exception) {
            promise.reject("PDF_CONVERSION_ERROR", "Failed to convert PDF to bitmaps: ${e.message}")
        }
    }
}