using System;
using ArchestrA.MxAccess;

namespace MxAccess.Cli.Mx
{
    public enum MxUpdateKind
    {
        DataChange,
        WriteComplete,
        OperationComplete,
    }

    public sealed class MxUpdate
    {
        public MxUpdateKind Kind { get; init; }
        public int ItemHandle { get; init; }
        public string ItemReference { get; init; }
        public object Value { get; init; }
        public int Quality { get; init; }
        public DateTime? Timestamp { get; init; }
        public MxStatusInfo[] Statuses { get; init; }

        public bool IsOk
        {
            get
            {
                if (Statuses == null || Statuses.Length == 0) return true;
                foreach (var s in Statuses)
                {
                    if (s.Category != MxStatusCategory.MxCategoryOk &&
                        s.Category != MxStatusCategory.MxCategoryPending)
                        return false;
                }
                return true;
            }
        }
    }

    public sealed class MxStatusInfo
    {
        public short Success { get; init; }
        public MxStatusCategory Category { get; init; }
        public MxStatusSource DetectedBy { get; init; }
        public short Detail { get; init; }

        public static MxStatusInfo[] From(MXSTATUS_PROXY[] raw)
        {
            if (raw == null) return Array.Empty<MxStatusInfo>();
            var output = new MxStatusInfo[raw.Length];
            for (int i = 0; i < raw.Length; i++)
            {
                output[i] = new MxStatusInfo
                {
                    Success    = raw[i].success,
                    Category   = raw[i].category,
                    DetectedBy = raw[i].detectedBy,
                    Detail     = raw[i].detail,
                };
            }
            return output;
        }

        public override string ToString() =>
            $"{Category} (success={Success}, detail={Detail}, detectedBy={DetectedBy})";
    }
}
