package com.agilex.healthcare.schedulingmanager.datalayer.pdf;


import com.agilex.healthcare.schedulingmanager.pdf.ConsultPdfPageFactory;
import com.agilex.healthcare.schedulingmanager.pdf.PageEvent;
import com.agilex.healthcare.schedulingmanager.pdf.PdfGenerationContext;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.PageSize;
import com.lowagie.text.pdf.PdfWriter;
import org.apache.log4j.Logger;
import com.lowagie.text.Rectangle;

import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
import java.awt.*;
import java.io.OutputStream;

public class PdfDataLayerItext implements PdfDataLayer{
    private static final Logger LOGGER = Logger.getLogger(PdfDataLayerItext.class);
    Document document;

    public PdfDataLayerItext() {
        initializeDocument();
    }

    private void initializeDocument() {
        Rectangle pageSize = new Rectangle(PageSize.A4);
        pageSize.setBackgroundColor(new Color(0xFF, 0xFF, 0xFF));
        document = new Document(pageSize);
        document.setMargins(45, 45, 60, 45);
    }

    @Override
    public void generateConsultPdf(OutputStream outputStream, PdfGenerationContext context) {
        try {
            PageEvent event = new PageEvent(context);
            PdfWriter writer = PdfWriter.getInstance(document, outputStream);
            writer.setLinearPageMode();
            writer.setPageEvent(event);
            document.open();
            createPages(event, writer, context);
            document.close();
        } catch (DocumentException e) {
            LOGGER.error(e);
            throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
        }
    }

    private void createPages(PageEvent event, PdfWriter writer, PdfGenerationContext context){
        ConsultPdfPageFactory consultPdfPageFactory = new ConsultPdfPageFactory(document, event, writer, context);
        consultPdfPageFactory.createCoverPage();

    }
}
