using System.Globalization;
using ZB.MOM.WW.MxGateway.Contracts.Proto;

namespace ZB.MOM.WW.MxGateway.Server.Dashboard;

/// <summary>
///     Formats an <see cref="MxValue"/> into the short, human-readable text the
///     dashboard's Browse subscription panel shows. Kept separate from the
///     view layer so the formatting rules are unit-testable without a worker.
/// </summary>
public static class DashboardMxValueFormatter
{
    /// <summary>Maximum array elements rendered inline before the value is truncated.</summary>
    private const int MaxArrayElements = 24;

    /// <summary>Formats the value payload of an <see cref="MxValue"/>.</summary>
    /// <param name="value">The value to format; may be null.</param>
    /// <returns>A display string — never null.</returns>
    public static string FormatValue(MxValue? value)
    {
        if (value is null)
        {
            return "-";
        }

        if (value.IsNull)
        {
            return "(null)";
        }

        return value.KindCase switch
        {
            MxValue.KindOneofCase.BoolValue => value.BoolValue ? "true" : "false",
            MxValue.KindOneofCase.Int32Value => value.Int32Value.ToString(CultureInfo.InvariantCulture),
            MxValue.KindOneofCase.Int64Value => value.Int64Value.ToString(CultureInfo.InvariantCulture),
            MxValue.KindOneofCase.FloatValue => value.FloatValue.ToString("G7", CultureInfo.InvariantCulture),
            MxValue.KindOneofCase.DoubleValue => value.DoubleValue.ToString("G15", CultureInfo.InvariantCulture),
            MxValue.KindOneofCase.StringValue => value.StringValue,
            MxValue.KindOneofCase.TimestampValue => value.TimestampValue
                .ToDateTimeOffset()
                .UtcDateTime
                .ToString("yyyy-MM-dd HH:mm:ss.fff 'UTC'", CultureInfo.InvariantCulture),
            MxValue.KindOneofCase.ArrayValue => FormatArray(value.ArrayValue),
            MxValue.KindOneofCase.RawValue => $"({value.RawValue.Length} bytes)",
            _ => "-",
        };
    }

    /// <summary>Formats the MXAccess data type of an <see cref="MxValue"/>.</summary>
    /// <param name="value">The value whose data type to describe; may be null.</param>
    /// <returns>The data-type name — never null. Arrays render as <c>Element[dims]</c>.</returns>
    public static string FormatDataType(MxValue? value)
    {
        if (value is null)
        {
            return "-";
        }

        // A scalar carries its type in MxValue.DataType, but an array leaves
        // that Unspecified and carries the element type on the MxArray itself.
        return value.KindCase == MxValue.KindOneofCase.ArrayValue
            ? FormatArrayDataType(value.ArrayValue)
            : value.DataType.ToString();
    }

    private static string FormatArrayDataType(MxArray array)
    {
        string dimensions = array.Dimensions.Count > 0
            ? string.Join(",", array.Dimensions)
            : string.Empty;
        return $"{array.ElementDataType}[{dimensions}]";
    }

    private static string FormatArray(MxArray array)
    {
        IReadOnlyList<string> elements = array.ValuesCase switch
        {
            MxArray.ValuesOneofCase.BoolValues =>
                array.BoolValues.Values.Select(item => item ? "true" : "false").ToArray(),
            MxArray.ValuesOneofCase.Int32Values =>
                array.Int32Values.Values.Select(item => item.ToString(CultureInfo.InvariantCulture)).ToArray(),
            MxArray.ValuesOneofCase.Int64Values =>
                array.Int64Values.Values.Select(item => item.ToString(CultureInfo.InvariantCulture)).ToArray(),
            MxArray.ValuesOneofCase.FloatValues =>
                array.FloatValues.Values.Select(item => item.ToString("G7", CultureInfo.InvariantCulture)).ToArray(),
            MxArray.ValuesOneofCase.DoubleValues =>
                array.DoubleValues.Values.Select(item => item.ToString("G15", CultureInfo.InvariantCulture)).ToArray(),
            MxArray.ValuesOneofCase.StringValues =>
                array.StringValues.Values.Select(item => $"\"{item}\"").ToArray(),
            MxArray.ValuesOneofCase.TimestampValues =>
                array.TimestampValues.Values
                    .Select(item => item.ToDateTimeOffset().UtcDateTime
                        .ToString("yyyy-MM-dd HH:mm:ss 'UTC'", CultureInfo.InvariantCulture))
                    .ToArray(),
            MxArray.ValuesOneofCase.RawValues =>
                array.RawValues.Values.Select(item => $"({item.Length} bytes)").ToArray(),
            _ => [],
        };

        if (elements.Count == 0)
        {
            return "[]";
        }

        string body = string.Join(", ", elements.Take(MaxArrayElements));
        return elements.Count > MaxArrayElements
            ? $"[{body}, … {elements.Count} total]"
            : $"[{body}]";
    }
}
