using CliFx.Attributes;
using CliFx.Exceptions;
using CliFx.Infrastructure;
using Opc.Ua;
using ZB.MOM.WW.OtOpcUa.Client.CLI.Helpers;
using ZB.MOM.WW.OtOpcUa.Client.Shared;

namespace ZB.MOM.WW.OtOpcUa.Client.CLI.Commands;

[Command("ack", Description = "Acknowledge an active alarm condition (OPC UA Part 9)")]
public class AcknowledgeCommand : CommandBase
{
    /// <summary>
    /// Creates the acknowledge command used to acknowledge an active OPC UA condition from the terminal.
    /// </summary>
    /// <param name="factory">The factory that creates the shared client service for the command run.</param>
    public AcknowledgeCommand(IOpcUaClientServiceFactory factory) : base(factory)
    {
    }

    /// <summary>
    /// Gets the condition node ID of the alarm event to acknowledge.
    /// </summary>
    [CommandOption("node", 'n', Description = "Condition node ID of the alarm to acknowledge", IsRequired = true)]
    public string NodeId { get; init; } = default!;

    /// <summary>
    /// Gets the event ID (hex-encoded) returned by the server in the alarm notification.
    /// </summary>
    [CommandOption("event-id", 'e', Description = "EventId from the alarm notification (hex-encoded byte array)", IsRequired = true)]
    public string EventId { get; init; } = default!;

    /// <summary>
    /// Gets the operator comment to include with the acknowledgment.
    /// </summary>
    [CommandOption("comment", 'c', Description = "Operator comment for the acknowledgment")]
    public string Comment { get; init; } = string.Empty;

    /// <inheritdoc />
    public override async ValueTask ExecuteAsync(IConsole console)
    {
        ConfigureLogging();

        try
        {
            NodeIdParser.ParseRequired(NodeId);
        }
        catch (Exception ex) when (ex is FormatException or ArgumentException)
        {
            throw new CommandException($"Invalid --node value: {ex.Message}");
        }

        byte[] eventId;
        try
        {
            eventId = Convert.FromHexString(EventId);
        }
        catch (FormatException ex)
        {
            throw new CommandException($"Invalid --event-id value: {ex.Message} (expected hex-encoded bytes, e.g. 0A1B2C)");
        }

        IOpcUaClientService? service = null;
        try
        {
            var ct = console.RegisterCancellationHandler();
            (service, _) = await CreateServiceAndConnectAsync(ct);

            var statusCode = await service.AcknowledgeAlarmAsync(NodeId, eventId, Comment, ct);

            if (StatusCode.IsGood(statusCode))
                await console.Output.WriteLineAsync($"Acknowledge successful: {NodeId}");
            else
                await console.Output.WriteLineAsync($"Acknowledge failed: {statusCode}");
        }
        finally
        {
            if (service != null)
            {
                await service.DisconnectAsync();
                service.Dispose();
            }
        }
    }
}
