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

/// <summary>
///     Maps FOCAS / FWLIB return codes to OPC UA StatusCodes. The FWLIB C API uses an
///     <c>EW_*</c> constant family per the Fanuc FOCAS/1 and FOCAS/2 documentation
///     (<c>EW_OK = 0</c>, <c>EW_NUMBER</c>, <c>EW_SOCKET</c>, etc.). Mirrors the shape of the
///     AbCip / TwinCAT mappers so Admin UI status displays stay uniform across drivers.
/// </summary>
public static class FocasStatusMapper
{
    public const uint Good = 0u;
    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 = 0x808B0000u;
    public const uint BadCommunicationError = 0x80050000u;
    public const uint BadTimeout = 0x800A0000u;
    public const uint BadTypeMismatch = 0x80740000u;

    /// <summary>
    ///     Map common FWLIB <c>EW_*</c> return codes. The values below match Fanuc's published
    ///     numeric conventions (EW_OK=0, EW_FUNC=1, EW_NUMBER=3, EW_LENGTH=4, EW_ATTRIB=7,
    ///     EW_DATA=8, EW_NOOPT=6, EW_PROT=5, EW_OVRFLOW=2, EW_PARITY=9, EW_PASSWD=11,
    ///     EW_BUSY=-1, EW_HANDLE=-8, EW_VERSION=-9, EW_UNEXP=-10, EW_SOCKET=-16).
    /// </summary>
    /// <param name="ret">The FWLIB return code.</param>
    /// <returns>The corresponding OPC UA status code.</returns>
    public static uint MapFocasReturn(int ret) => ret switch
    {
        0 => Good,
        1 => BadNotSupported,          // EW_FUNC — CNC does not support this function
        2 => BadOutOfRange,            // EW_OVRFLOW
        3 => BadOutOfRange,            // EW_NUMBER
        4 => BadOutOfRange,            // EW_LENGTH
        5 => BadNotWritable,           // EW_PROT
        6 => BadNotSupported,          // EW_NOOPT — optional CNC feature missing
        7 => BadTypeMismatch,          // EW_ATTRIB
        8 => BadNodeIdUnknown,         // EW_DATA — invalid data address
        9 => BadCommunicationError,    // EW_PARITY
        11 => BadNotWritable,          // EW_PASSWD
        -1 => BadDeviceFailure,        // EW_BUSY
        -8 => BadInternalError,        // EW_HANDLE — CNC handle not available
        -9 => BadNotSupported,         // EW_VERSION — FWLIB vs CNC version mismatch
        -10 => BadCommunicationError,  // EW_UNEXP
        -16 => BadCommunicationError,  // EW_SOCKET
        _ => BadCommunicationError,
    };
}
