package de.cannamanage.service;

import com.lowagie.text.Document;
import com.lowagie.text.Element;
import com.lowagie.text.Font;
import com.lowagie.text.Phrase;
import com.lowagie.text.Rectangle;
import com.lowagie.text.pdf.ColumnText;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfPageEventHelper;
import com.lowagie.text.pdf.PdfWriter;

import java.awt.Color;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * PDF footer event handler.
 * Adds "Erstellt am: dd.MM.yyyy HH:mm" left-aligned and "Seite N" right-aligned
 * at the bottom of every page.
 */
public class PdfFooterHandler extends PdfPageEventHelper {

    private static final Font FOOTER_FONT = new Font(Font.HELVETICA, 8, Font.NORMAL, Color.GRAY);
    private static final DateTimeFormatter FOOTER_DATE_FORMAT = DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm");

    private final String generatedTimestamp;

    public PdfFooterHandler() {
        this.generatedTimestamp = LocalDateTime.now().format(FOOTER_DATE_FORMAT);
    }

    @Override
    public void onEndPage(PdfWriter writer, Document document) {
        PdfContentByte cb = writer.getDirectContent();
        Rectangle pageSize = document.getPageSize();
        float bottom = document.bottomMargin() - 15;

        // Left: "Erstellt am: dd.MM.yyyy HH:mm"
        ColumnText.showTextAligned(cb, Element.ALIGN_LEFT,
                new Phrase("Erstellt am: " + generatedTimestamp, FOOTER_FONT),
                document.leftMargin(), bottom, 0);

        // Right: "Seite N"
        ColumnText.showTextAligned(cb, Element.ALIGN_RIGHT,
                new Phrase("Seite " + writer.getPageNumber(), FOOTER_FONT),
                pageSize.getWidth() - document.rightMargin(), bottom, 0);
    }
}
