using System.Text;

namespace Inspectron.Epson.PrintServer.Telemetry;

public static class InsinMessageFormatter
{
    public static string Format(params (string Key, string? Value)[] pairs)
    {
        var sb = new StringBuilder();
        foreach (var (key, value) in pairs)
        {
            if (string.IsNullOrEmpty(key)) continue;
            if (sb.Length > 0) sb.Append(' ');
            sb.Append(key).Append('=').Append(FormatValue(value));
        }
        return sb.ToString();
    }

    private static string FormatValue(string? value)
    {
        if (string.IsNullOrEmpty(value)) return string.Empty;
        if (value.IndexOf(' ') < 0 && value.IndexOf('"') < 0) return value;
        var escaped = value.Replace("\\", "\\\\").Replace("\"", "\\\"");
        return $"\"{escaped}\"";
    }
}
