using System.Reflection;
using System.Text;
using System.Text.Json.Serialization;
using Quadarax.Foundation.Core.Data;

namespace Quadarax.Foundation.Core.QMonitor
{
    [Serializable]
    public class MonItemGeneral
    {
        [JsonPropertyName("nam")]
        public string? Name { get; set; }
        [JsonPropertyName("cpt")]
        public string Caption { get; set; }
        [JsonPropertyName("dsc")]
        public string Description { get; set; }
        [JsonPropertyName("vty")]
        public MonViewType ViewType { get; set; }
        [JsonPropertyName("key")]
        public List<int> KeyOrdinals { get; set; } = new List<int>();

        public List<ItemDescriptor> Items { get; set; } = new List<ItemDescriptor>();


        public string GetKeyAsString(TypedArgument[] values)
        {
            if (values== null) throw new ArgumentNullException(nameof(values));
            var sb = new StringBuilder();
            foreach (var key in KeyOrdinals)
            {
                var item = Items[key];
                var val = values.FirstOrDefault(x =>
                    string.Equals(x.Name, item.Name, StringComparison.InvariantCultureIgnoreCase));
                if (val == null) throw new InvalidOperationException($"Key {item.Name} not found in provided values.");
                sb.Append(val.Value).Append("_");
            }

            var result = sb.ToString();

            if (result.Equals("_"))
                result = result.Remove(result.Length - 1, 1);
            return result;
        }


        public class ItemDescriptor
        {
            [JsonPropertyName("nme")]
            public string Name { get; set; }
            [JsonPropertyName("tnm")]
            public string TypeName { get; set; }
            [JsonPropertyName("lbl")]
            public string Label { get; set; }
            [JsonPropertyName("dsc")]
            public string Description { get; set; }
            [JsonPropertyName("ord")]
            public int Order { get; set; }

            [NonSerialized] public PropertyInfo? _propertyInfo;

        }

        public enum MonViewType
        {
            Item,
            List
        }
    }
}
