using System.Text.Json;
using Inspectron.Epson.PrintServer.Printers.Utils;
using Inspectron.Epson.TemplateEngine.DataBinding;
using Inspectron.Epson.TemplateEngine.Parsing;
using Inspectron.Epson.TemplateEngine.Rendering;

namespace Inspectron.Epson.TemplateEngine;

public class ReceiptTemplateEngine
{
    public List<PrintCommand> Render(
        string xmlTemplate,
        string jsonData,
        int lineWidth = 48,
        int bigFontLineWidth = 24)
    {
        // Parse XML template into node tree
        var parser = new TemplateParser();
        var receiptNode = parser.Parse(xmlTemplate);

        // Parse JSON data into DataContext
        JsonElement root;
        try
        {
            root = JsonDocument.Parse(jsonData).RootElement;
        }
        catch (JsonException ex)
        {
            throw new TemplateRenderingException($"Invalid JSON data: {ex.Message}", ex);
        }

        var context = new DataContext(root);

        // Render node tree to PrintCommands
        var renderer = new TemplateRenderer(lineWidth, bigFontLineWidth);
        return renderer.Render(receiptNode, context);
    }
}
