package com.isidroid.ms_office

import com.itextpdf.kernel.pdf.PdfDocument
import com.itextpdf.kernel.pdf.PdfWriter
import com.itextpdf.layout.Document
import com.itextpdf.layout.element.Paragraph
import org.apache.poi.hwpf.HWPFDocument
import org.apache.poi.hwpf.extractor.WordExtractor
import timber.log.Timber
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream


fun convertDocToPdf(docFile: File): File {
    val pdfFile = File(docFile.parent, "${docFile.nameWithoutExtension}.pdf")

    Timber.i("===> docFile=$docFile, exists=${docFile.exists()}")

    // Read input DOC file
    val doc = HWPFDocument(FileInputStream(docFile))
    val extractor = WordExtractor(doc)

    // Create output PDF file
    val pdfWriter = PdfWriter(FileOutputStream(pdfFile))
    val pdf = PdfDocument(pdfWriter)
    val document = Document(pdf)

    try {
        // Extract text from DOC file
        val text = extractor.text

        // Split text into paragraphs
        val paragraphs = text.split("\\\$\\{([^}]*)}")

        // Add each paragraph to PDF document
        for (paragraphText in paragraphs) {
            val pdfParagraph = Paragraph(paragraphText)
            document.add(pdfParagraph)
        }

        // Close the document
//        document.close()
    } catch (e: Exception) {
        println("Error converting document to PDF: ${e.message}")
    } finally {
        // Close all resources
        try {
//            pdf.close()
        } catch (e: Exception) {
            println("Error closing PDF document: ${e.message}")
        }

        try {
//            pdfWriter.close()
        } catch (e: Exception) {
            println("Error closing PDF writer: ${e.message}")
        }

        try {
//            doc.close()
        } catch (e: Exception) {
            println("Error closing Word document: ${e.message}")
        }
    }


    return pdfFile
}