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("enable", Description = "Enable an alarm condition (OPC UA Part 9 ConditionType Enable)")]
public class EnableCommand : CommandBase
{
    /// <summary>
    /// Creates the enable command used to enable an OPC UA alarm condition from the terminal.
    /// </summary>
    /// <param name="factory">The factory that creates the shared client service for the command run.</param>
    public EnableCommand(IOpcUaClientServiceFactory factory) : base(factory)
    {
    }

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

    /// <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}");
        }

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

            var statusCode = await service.EnableAsync(NodeId, ct);

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