package com.betriebsratkanzlei.legalconsenthub.application_form

import org.springframework.stereotype.Service
import org.thymeleaf.TemplateEngine
import org.thymeleaf.context.Context
import java.io.ByteArrayOutputStream
import com.openhtmltopdf.pdfboxout.PdfRendererBuilder

@Service
class ApplicationFormFormatService(
    private val templateEngine: TemplateEngine
) {
    fun generatePdf(applicationForm: ApplicationForm): ByteArray {
        val htmlContent = generateHtml(applicationForm)

        val outputStream = ByteArrayOutputStream()
        PdfRendererBuilder().useFastMode()
            .withHtmlContent(htmlContent, null)
            .toStream(outputStream)
            .run()

        return outputStream.toByteArray()
    }

    fun generateHtml(applicationForm: ApplicationForm): String {
        val context = Context().apply {
            setVariable("applicationForm", applicationForm)
        }
        return templateEngine.process("application_form_template", context)
    }
}
