namespace EpsonReceiptPrinter;

public static class ReceiptFormatter
{
    public static byte[] Format(Receipt receipt, PrinterCodePage codePage = PrinterCodePage.PC865_Nordic)
    {
        ArgumentNullException.ThrowIfNull(receipt);

        var width = receipt.PaperWidthCharacters <= 0 ? 42 : receipt.PaperWidthCharacters;

        var builder = new EscPosBuilder(codePage)
            .Initialize()
            .AlignCenter();

        if (!string.IsNullOrWhiteSpace(receipt.Header))
        {
            builder
                .SetTextSize(TextSize.DoubleWidthAndHeight)
                .BoldOn()
                .WriteLine(receipt.Header)
                .BoldOff()
                .SetTextSize(TextSize.Normal);
        }

        if (!string.IsNullOrWhiteSpace(receipt.SubHeader))
        {
            builder.WriteLine(receipt.SubHeader);
        }

        builder
            .Feed(1)
            .AlignLeft()
            .Separator(width);

        foreach (var line in receipt.Lines)
        {
            builder.SetTextSize(line.TextSize);

            if (line.Emphasize)
            {
                builder.BoldOn();
            }
            else
            {
                builder.BoldOff();
            }

            builder.WriteColumns(line.Left, line.Right, width);
            builder.SetTextSize(TextSize.Normal);
            builder.BoldOff();
        }

        builder
            .Separator(width)
            .Feed(1)
            .AlignCenter();

        if (!string.IsNullOrWhiteSpace(receipt.Footer))
        {
            builder.WriteLine(receipt.Footer);
        }

        builder.Feed(3);

        if (receipt.CutPaper)
        {
            builder.Cut();
        }

        return builder.Build();
    }
}
