using CliFx.Attributes;
using CliFx.Infrastructure;
using ZB.MOM.WW.OtOpcUa.Driver.Cli.Common;

namespace ZB.MOM.WW.OtOpcUa.Driver.FOCAS.Cli.Commands;

/// <summary>
///     Read one FOCAS address (PMC R/G/F file, parameter, macro, axis register).
/// </summary>
[Command("read", Description = "Read a single FOCAS address.")]
public sealed class ReadCommand : FocasCommandBase
{
    [CommandOption("address", 'a', Description =
        "FOCAS address. Examples: R100 (PMC R-file word); X0.0 (PMC X-bit); " +
        "PARAM:1815/0 (parameter 1815, axis 0); MACRO:500 (macro variable 500).",
        IsRequired = true)]
    public string Address { get; init; } = default!;

    [CommandOption("type", 't', Description =
        "Bit / Byte / Int16 / Int32 / Float32 / Float64 / String (default Int16).")]
    public FocasDataType DataType { get; init; } = FocasDataType.Int16;

    public override async ValueTask ExecuteAsync(IConsole console)
    {
        ConfigureLogging();
        var ct = console.RegisterCancellationHandler();

        var tagName = SynthesiseTagName(Address, DataType);
        var tag = new FocasTagDefinition(
            Name: tagName,
            DeviceHostAddress: HostAddress,
            Address: Address,
            DataType: DataType,
            Writable: false);
        var options = BuildOptions([tag]);

        await using var driver = new FocasDriver(options, DriverInstanceId);
        try
        {
            await driver.InitializeAsync("{}", ct);
            var snapshot = await driver.ReadAsync([tagName], ct);
            await console.Output.WriteLineAsync(SnapshotFormatter.Format(Address, snapshot[0]));
        }
        finally
        {
            await driver.ShutdownAsync(CancellationToken.None);
        }
    }

    internal static string SynthesiseTagName(string address, FocasDataType type)
        => $"{address}:{type}";
}
