using System.Text.Json;
using System.Text.Json.Serialization;

namespace ScadaLink.CLI;

public static class OutputFormatter
{
    private static readonly JsonSerializerOptions JsonOptions = new()
    {
        WriteIndented = true,
        DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
        PropertyNamingPolicy = JsonNamingPolicy.CamelCase
    };

    public static void WriteJson(object? data)
    {
        Console.WriteLine(JsonSerializer.Serialize(data, JsonOptions));
    }

    public static void WriteError(string message, string code)
    {
        Console.Error.WriteLine(JsonSerializer.Serialize(new { error = message, code }, JsonOptions));
    }

    public static void WriteTable(IEnumerable<string[]> rows, string[] headers)
    {
        var allRows = new List<string[]> { headers };
        allRows.AddRange(rows);
        var widths = new int[headers.Length];
        foreach (var row in allRows)
            for (int i = 0; i < Math.Min(row.Length, widths.Length); i++)
                widths[i] = Math.Max(widths[i], (row[i] ?? "").Length);

        foreach (var row in allRows)
        {
            for (int i = 0; i < headers.Length; i++)
                Console.Write((i < row.Length ? row[i] ?? "" : "").PadRight(widths[i] + 2));
            Console.WriteLine();
        }
    }
}
