using libplctag;

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

/// <summary>
///     Default libplctag-backed <see cref="IAbCipTagRuntime"/>. Wraps a <see cref="Tag"/>
///     instance + translates our <see cref="AbCipDataType"/> enum into the
///     <c>GetInt32</c> / <c>GetFloat32</c> / <c>GetString</c> / <c>GetBit</c> calls libplctag
///     exposes. One runtime instance per <c>(device, tag path)</c>; lifetime is owned by the
///     driver's per-device state dict.
/// </summary>
internal sealed class LibplctagTagRuntime : IAbCipTagRuntime
{
    private readonly Tag _tag;

    /// <summary>Initializes a new instance of the LibplctagTagRuntime class.</summary>
    /// <param name="p">The tag creation parameters.</param>
    public LibplctagTagRuntime(AbCipTagCreateParams p)
    {
        _tag = new Tag
        {
            Gateway = p.Gateway,
            Path = p.CipPath,
            PlcType = MapPlcType(p.LibplctagPlcAttribute),
            Protocol = Protocol.ab_eip,
            Name = p.TagName,
            Timeout = p.Timeout,
            // Driver.AbCip-013 — honour the per-device or family-default AllowPacking knob so
            // operators can disable CIP request-packing for older firmware or a single device.
            AllowPacking = p.AllowPacking,
        };
        // ConnectionSize is captured on AbCipTagCreateParams for forward-compat (driver-specs.md
        // exposes it as a per-device option) but libplctag.NET 1.5.2 has no direct Tag property
        // for it. Until the wrapper exposes one (or we ship a custom tag-attribute path), the
        // family profile DefaultConnectionSize is what the underlying CIP Forward Open
        // negotiates with — Driver.AbCip-013.
    }

    /// <summary>Initializes the tag asynchronously.</summary>
    /// <param name="cancellationToken">The cancellation token.</param>
    /// <returns>A task representing the asynchronous initialization.</returns>
    public Task InitializeAsync(CancellationToken cancellationToken) => _tag.InitializeAsync(cancellationToken);

    /// <summary>Reads the tag value asynchronously.</summary>
    /// <param name="cancellationToken">The cancellation token.</param>
    /// <returns>A task representing the asynchronous read operation.</returns>
    public Task ReadAsync(CancellationToken cancellationToken) => _tag.ReadAsync(cancellationToken);

    /// <summary>Writes the tag value asynchronously.</summary>
    /// <param name="cancellationToken">The cancellation token.</param>
    /// <returns>A task representing the asynchronous write operation.</returns>
    public Task WriteAsync(CancellationToken cancellationToken) => _tag.WriteAsync(cancellationToken);

    /// <summary>Gets the current status of the tag.</summary>
    /// <returns>The tag status as an integer.</returns>
    public int GetStatus() => (int)_tag.GetStatus();

    /// <summary>Decodes the tag value with the specified data type.</summary>
    /// <param name="type">The data type to decode.</param>
    /// <param name="bitIndex">The bit index for bit-level access, if applicable.</param>
    /// <returns>The decoded value.</returns>
    public object? DecodeValue(AbCipDataType type, int? bitIndex) => DecodeValueAt(type, 0, bitIndex);

    /// <summary>Decodes the tag value at the specified offset with the specified data type.</summary>
    /// <param name="type">The data type to decode.</param>
    /// <param name="offset">The byte offset within the tag buffer.</param>
    /// <param name="bitIndex">The bit index for bit-level access, if applicable.</param>
    /// <returns>The decoded value.</returns>
    public object? DecodeValueAt(AbCipDataType type, int offset, int? bitIndex) => type switch
    {
        AbCipDataType.Bool => bitIndex is int bit
            ? _tag.GetBit(bit)
            : _tag.GetInt8(offset) != 0,
        AbCipDataType.SInt => (int)(sbyte)_tag.GetInt8(offset),
        AbCipDataType.USInt => (int)_tag.GetUInt8(offset),
        AbCipDataType.Int => (int)_tag.GetInt16(offset),
        AbCipDataType.UInt => (int)_tag.GetUInt16(offset),
        AbCipDataType.DInt => _tag.GetInt32(offset),
        AbCipDataType.UDInt => _tag.GetUInt32(offset),      // UInt32 to match ToDriverDataType (Driver.AbCip-004)
        AbCipDataType.LInt => _tag.GetInt64(offset),         // Int64 to match ToDriverDataType (Driver.AbCip-004)
        AbCipDataType.ULInt => _tag.GetUInt64(offset),       // UInt64 to match ToDriverDataType (Driver.AbCip-004)
        AbCipDataType.Real => _tag.GetFloat32(offset),
        AbCipDataType.LReal => _tag.GetFloat64(offset),
        AbCipDataType.String => _tag.GetString(offset),
        AbCipDataType.Dt => _tag.GetInt32(offset),
        AbCipDataType.Structure => null,
        _ => null,
    };

    /// <summary>Encodes the specified value to the tag with the specified data type.</summary>
    /// <param name="type">The data type to encode.</param>
    /// <param name="bitIndex">The bit index for bit-level access, if applicable.</param>
    /// <param name="value">The value to encode.</param>
    public void EncodeValue(AbCipDataType type, int? bitIndex, object? value)
    {
        switch (type)
        {
            case AbCipDataType.Bool:
                if (bitIndex is int)
                {
                    // BOOL-within-DINT writes are routed at the driver level (AbCipDriver.
                    // WriteBitInDIntAsync) via a parallel parent-DINT runtime so the RMW stays
                    // serialised. If one reaches here it means the driver dispatch was bypassed —
                    // throw so the error surfaces loudly rather than clobbering the whole DINT.
                    throw new NotSupportedException(
                        "BOOL-with-bitIndex writes must go through AbCipDriver.WriteBitInDIntAsync, not LibplctagTagRuntime.");
                }
                _tag.SetInt8(0, Convert.ToBoolean(value) ? (sbyte)1 : (sbyte)0);
                break;
            case AbCipDataType.SInt:
                _tag.SetInt8(0, Convert.ToSByte(value));
                break;
            case AbCipDataType.USInt:
                _tag.SetUInt8(0, Convert.ToByte(value));
                break;
            case AbCipDataType.Int:
                _tag.SetInt16(0, Convert.ToInt16(value));
                break;
            case AbCipDataType.UInt:
                _tag.SetUInt16(0, Convert.ToUInt16(value));
                break;
            case AbCipDataType.DInt:
                _tag.SetInt32(0, Convert.ToInt32(value));
                break;
            case AbCipDataType.UDInt:
                _tag.SetUInt32(0, Convert.ToUInt32(value));
                break;
            case AbCipDataType.LInt:
                _tag.SetInt64(0, Convert.ToInt64(value));
                break;
            case AbCipDataType.ULInt:
                _tag.SetUInt64(0, Convert.ToUInt64(value));
                break;
            case AbCipDataType.Real:
                _tag.SetFloat32(0, Convert.ToSingle(value));
                break;
            case AbCipDataType.LReal:
                _tag.SetFloat64(0, Convert.ToDouble(value));
                break;
            case AbCipDataType.String:
                _tag.SetString(0, Convert.ToString(value) ?? string.Empty);
                break;
            case AbCipDataType.Dt:
                _tag.SetInt32(0, Convert.ToInt32(value));
                break;
            case AbCipDataType.Structure:
                // Whole-UDT writes are not implemented — operators address individual UDT
                // members via dotted tag paths, which route per-member through the atomic
                // encode cases above. A whole-UDT writer is a deferred follow-up.
                throw new NotSupportedException(
                    "Whole-UDT writes are not supported — address individual member paths instead.");
            default:
                throw new NotSupportedException($"AbCipDataType {type} not writable.");
        }
    }

    /// <summary>Disposes the tag and releases its resources.</summary>
    public void Dispose() => _tag.Dispose();

    private static PlcType MapPlcType(string attribute) => attribute switch
    {
        "controllogix" => PlcType.ControlLogix,
        "compactlogix" => PlcType.ControlLogix, // libplctag treats CompactLogix under ControlLogix family
        "micro800" => PlcType.Micro800,
        "micrologix" => PlcType.MicroLogix,
        "slc500" => PlcType.Slc500,
        "plc5" => PlcType.Plc5,
        "omron-njnx" => PlcType.Omron,
        _ => PlcType.ControlLogix,
    };
}

/// <summary>
///     Default <see cref="IAbCipTagFactory"/> — creates a fresh <see cref="LibplctagTagRuntime"/>
///     per call. Stateless; safe to share across devices.
/// </summary>
/// <summary>Default implementation of IAbCipTagFactory that creates LibplctagTagRuntime instances.</summary>
internal sealed class LibplctagTagFactory : IAbCipTagFactory
{
    /// <summary>Creates a new tag runtime with the specified creation parameters.</summary>
    /// <param name="createParams">The parameters for creating the tag.</param>
    /// <returns>A new IAbCipTagRuntime instance.</returns>
    public IAbCipTagRuntime Create(AbCipTagCreateParams createParams) =>
        new LibplctagTagRuntime(createParams);
}
