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

/// <summary>
///     Maps AMS / ADS error codes to OPC UA StatusCodes. ADS error codes are defined in
///     <c>AdsErrorCode</c> from <c>Beckhoff.TwinCAT.Ads</c> — this mapper covers the ones a
///     driver actually encounters during normal operation (symbol-not-found, access-denied,
///     timeout, router-not-initialized, invalid-group/offset, etc.).
/// </summary>
public static class TwinCATStatusMapper
{
    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 = 0x80550000u;
    public const uint BadCommunicationError = 0x80050000u;
    public const uint BadTimeout = 0x800A0000u;
    public const uint BadTypeMismatch = 0x80730000u;

    /// <summary>
    ///     Map an AMS / ADS error code (uint from AdsErrorCode enum). 0 = success; non-zero
    ///     codes follow Beckhoff's AMS error table (7 = target port not found, 1792 =
    ///     ADSERR_DEVICE_SRVNOTSUPP, 1793 = ADSERR_DEVICE_INVALIDGRP, 1794 =
    ///     ADSERR_DEVICE_INVALIDOFFSET, 1798 = ADSERR_DEVICE_SYMBOLNOTFOUND, 1808 =
    ///     ADSERR_DEVICE_ACCESSDENIED, 1861 = ADSERR_CLIENT_SYNCTIMEOUT).
    /// </summary>
    public static uint MapAdsError(uint adsError) => adsError switch
    {
        0 => Good,
        6 or 7 => BadCommunicationError,           // target port unreachable
        1792 => BadNotSupported,                    // service not supported
        1793 => BadOutOfRange,                      // invalid index group
        1794 => BadOutOfRange,                      // invalid index offset
        1798 => BadNodeIdUnknown,                   // symbol not found
        1807 => BadDeviceFailure,                   // device in invalid state
        1808 => BadNotWritable,                     // access denied
        1811 or 1812 => BadOutOfRange,              // size mismatch
        1861 => BadTimeout,                          // sync timeout
        _ => BadCommunicationError,
    };
}
