package fyloz.trial.ColorRecipesExplorer.factory.files;

import com.itextpdf.text.*;
import com.itextpdf.text.pdf.PdfWriter;
import fyloz.trial.ColorRecipesExplorer.ColorRecipesExplorerApplication;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

public class TouchUpKitPdfFactory {

    private String kitName;
    private ByteArrayOutputStream pdfContent;
    private Document document;

    public TouchUpKitPdfFactory(String kitName) {
        this.kitName = kitName.toUpperCase();

        pdfContent = new ByteArrayOutputStream();
        document = new Document();
    }

    public TouchUpKitPdfFactory build() throws DocumentException {
        ColorRecipesExplorerApplication.logger.info(String.format("Génération d'un PDF pour le kit de retouche '%s'", kitName));

        PdfWriter.getInstance(document, pdfContent);

        Font descFont = FontFactory.getFont(FontFactory.HELVETICA_BOLD, 48, BaseColor.BLACK);
        Font kitNameFont = FontFactory.getFont(FontFactory.HELVETICA_BOLD, kitName.length() > 22 ? 32 : 38, BaseColor.BLACK);

        Paragraph descFr = new Paragraph("KIT DE RETOUCHE", descFont);
        Paragraph descEn = new Paragraph("TOUCH UP KIT", descFont);
        Paragraph touchUpKitName = new Paragraph(kitName, kitNameFont);

        descFr.setAlignment(Element.ALIGN_CENTER);
        descEn.setAlignment(Element.ALIGN_CENTER);
        touchUpKitName.setAlignment(Element.ALIGN_CENTER);

        document.open();
        document.add(descFr);
        document.add(descEn);
        document.add(touchUpKitName);
        document.close();

        return this;
    }

    public byte[] toByteArray() {
        byte[] content = pdfContent.toByteArray();

        try {
            pdfContent.close();
        } catch (IOException e) {
            ColorRecipesExplorerApplication.logger.error("Une erreur est survenue lors de la fermeture d'un ByteArrayOutputStream", e);
        }

        return content;
    }
}
