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("read", Description = "Read a value from a node")]
public class ReadCommand : CommandBase
{
    /// <summary>
    /// Creates the point-read command used to inspect the current value of a node.
    /// </summary>
    /// <param name="factory">The factory that creates the shared client service for the command run.</param>
    public ReadCommand(IOpcUaClientServiceFactory factory) : base(factory)
    {
    }

    /// <summary>
    /// Gets the node whose current value should be read.
    /// </summary>
    [CommandOption("node", 'n', Description = "Node ID (e.g. ns=2;s=MyNode)", IsRequired = true)]
    public string NodeId { get; init; } = default!;

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

        NodeId nodeId;
        try
        {
            nodeId = 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 value = await service.ReadValueAsync(nodeId, ct);

            await console.Output.WriteLineAsync($"Node:        {NodeId}");
            await console.Output.WriteLineAsync($"Value:       {value.Value}");
            await console.Output.WriteLineAsync($"Status:      {value.StatusCode}");
            await console.Output.WriteLineAsync($"Source Time: {value.SourceTimestamp:O}");
            await console.Output.WriteLineAsync($"Server Time: {value.ServerTimestamp:O}");
        }
        finally
        {
            if (service != null)
            {
                await service.DisconnectAsync();
                service.Dispose();
            }
        }
    }
}
