using Opc.Ua;

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

/// <summary>
/// Formats OPC UA status codes as "0xHEX (description)".
/// </summary>
internal static class StatusCodeFormatter
{
    /// <summary>Formats an OPC UA status code as a hexadecimal code with description.</summary>
    /// <param name="statusCode">The OPC UA status code to format.</param>
    /// <returns>A formatted string in the form "0xHEX (description)".</returns>
    public static string Format(StatusCode statusCode)
    {
        var code = statusCode.Code;
        var hex = $"0x{code:X8}";

        // Try the SDK's browse name lookup first
        var name = StatusCodes.GetBrowseName(code);
        if (!string.IsNullOrEmpty(name))
            return $"{hex} ({name})";

        // Try masking to just the main code (top 16 bits) for sub-status codes
        var mainCode = code & 0xFFFF0000;
        if (mainCode != code)
        {
            name = StatusCodes.GetBrowseName(mainCode);
            if (!string.IsNullOrEmpty(name))
                return $"{hex} ({name})";
        }

        // Fallback to severity category
        if (StatusCode.IsGood(statusCode))
            return $"{hex} (Good)";
        if (StatusCode.IsBad(statusCode))
            return $"{hex} (Bad)";
        return $"{hex} (Uncertain)";
    }
}
