namespace ZB.MOM.WW.OtOpcUa.Driver.AbLegacy;

/// <summary>
///     Maps libplctag status codes + PCCC STS/EXT_STS bytes to OPC UA StatusCodes. Mirrors the
///     AbCip mapper — PCCC errors roughly align with CIP general-status in shape but with a
///     different byte vocabulary (PCCC STS nibble-low + EXT_STS on code 0x0F).
/// </summary>
public static class AbLegacyStatusMapper
{
    public const uint Good = 0u;
    public const uint GoodMoreData = 0x00A70000u;
    public const uint BadInternalError = 0x80020000u;
    public const uint BadNodeIdUnknown = 0x80340000u;
    public const uint BadNotWritable = 0x803B0000u;
    public const uint BadOutOfRange = 0x803C0000u;
    public const uint BadNotSupported = 0x803D0000u;
    public const uint BadDeviceFailure = 0x80550000u;
    public const uint BadCommunicationError = 0x80050000u;
    public const uint BadTimeout = 0x800A0000u;
    public const uint BadTypeMismatch = 0x80730000u;

    /// <summary>
    ///     Map libplctag return/status codes. Same polarity as the AbCip mapper — 0 success,
    ///     positive pending, negative error families.
    /// </summary>
    public static uint MapLibplctagStatus(int status)
    {
        if (status == 0) return Good;
        if (status > 0) return GoodMoreData;
        return status switch
        {
            -5 => BadTimeout,
            -7 => BadCommunicationError,
            -14 => BadNodeIdUnknown,
            -16 => BadNotWritable,
            -17 => BadOutOfRange,
            _ => BadCommunicationError,
        };
    }

    /// <summary>
    ///     Map a PCCC STS (status) byte. Common codes per AB PCCC reference:
    ///     0x00 = success, 0x10 = illegal command, 0x20 = bad address, 0x30 = protected,
    ///     0x40 = programmer busy, 0x50 = file locked, 0xF0 = extended status follows.
    /// </summary>
    public static uint MapPcccStatus(byte sts) => sts switch
    {
        0x00 => Good,
        0x10 => BadNotSupported,
        0x20 => BadNodeIdUnknown,
        0x30 => BadNotWritable,
        0x40 => BadDeviceFailure,
        0x50 => BadDeviceFailure,
        0xF0 => BadInternalError, // extended status not inspected at this layer
        _ => BadCommunicationError,
    };
}
