using CliFx.Attributes;
using CliFx.Infrastructure;
using ZB.MOM.WW.OtOpcUa.Client.Shared;

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

[Command("redundancy", Description = "Read redundancy state from an OPC UA server")]
public class RedundancyCommand : CommandBase
{
    /// <summary>
    /// Creates the redundancy-inspection command used to display service-level and partner-server status.
    /// </summary>
    /// <param name="factory">The factory that creates the shared client service for the command run.</param>
    public RedundancyCommand(IOpcUaClientServiceFactory factory) : base(factory)
    {
    }

    /// <inheritdoc />
    public override async ValueTask ExecuteAsync(IConsole console)
    {
        ConfigureLogging();
        IOpcUaClientService? service = null;
        try
        {
            var ct = console.RegisterCancellationHandler();
            (service, _) = await CreateServiceAndConnectAsync(ct);

            var info = await service.GetRedundancyInfoAsync(ct);

            await console.Output.WriteLineAsync($"Redundancy Mode:  {info.Mode}");
            await console.Output.WriteLineAsync($"Service Level:    {info.ServiceLevel}");

            if (info.ServerUris.Length > 0)
            {
                await console.Output.WriteLineAsync("Server URIs:");
                foreach (var uri in info.ServerUris) await console.Output.WriteLineAsync($"  - {uri}");
            }

            await console.Output.WriteLineAsync($"Application URI:  {info.ApplicationUri}");
        }
        finally
        {
            if (service != null)
            {
                await service.DisconnectAsync();
                service.Dispose();
            }
        }
    }
}
