using System;
using ArchestrA.GRAccess;

namespace ZB.MOM.WW.GRAccess.Cli.GRAccess
{
    internal static class GRAccessDiagnostics
    {
        public static string NormalizeNodeName(string nodeName)
        {
            if (string.IsNullOrWhiteSpace(nodeName))
                return string.Empty;

            var trimmed = nodeName.Trim();
            return trimmed == "." ? Environment.MachineName : trimmed;
        }

        public static string FormatCommandResult(string operation, ICommandResult result)
        {
            if (result == null)
                return $"{operation} failed: no GRAccess command result was returned.";

            if (result.Successful)
                return $"{operation}: OK";

            return $"{operation} failed: ID={result.ID} ({(int)result.ID}); Text='{result.Text}'; CustomMessage='{result.CustomMessage}'";
        }

        public static void ThrowIfFailed(ICommandResult result, string operation)
        {
            if (result != null && !result.Successful)
                throw new InvalidOperationException(FormatCommandResult(operation, result));
        }
    }
}
