using System.Collections;

namespace ZB.MOM.WW.OtOpcUa.Client.UI.Helpers;

/// <summary>
/// Formats OPC UA values for display, with array support.
/// </summary>
internal static class ValueFormatter
{
    /// <summary>Formats an OPC UA value for display, handling arrays and enumerables specially.</summary>
    /// <param name="value">The value to format, or null.</param>
    /// <returns>A string representation of the value suitable for display.</returns>
    public static string Format(object? value)
    {
        if (value is null) return "(null)";
        if (value is Array array) return FormatArray(array);
        if (value is IEnumerable enumerable and not string) return FormatEnumerable(enumerable);
        return value.ToString() ?? "(null)";
    }

    private static string FormatArray(Array array)
    {
        var elements = new string[array.Length];
        for (var i = 0; i < array.Length; i++)
            elements[i] = array.GetValue(i)?.ToString() ?? "null";
        return $"[{string.Join(",", elements)}]";
    }

    private static string FormatEnumerable(IEnumerable enumerable)
    {
        var items = new List<string>();
        foreach (var item in enumerable)
            items.Add(item?.ToString() ?? "null");
        return $"[{string.Join(",", items)}]";
    }
}
