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("disable", Description = "Disable an alarm condition (OPC UA Part 9 ConditionType Disable)")]
public class DisableCommand : CommandBase
{
    /// <summary>
    /// Creates the disable command used to disable 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 DisableCommand(IOpcUaClientServiceFactory factory) : base(factory)
    {
    }

    /// <summary>
    /// Gets the condition node ID of the alarm to disable.
    /// </summary>
    [CommandOption("node", 'n', Description = "Condition node ID of the alarm to disable", 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.DisableAsync(NodeId, ct);

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