using System;
using System.Collections.Generic;
using System.Linq;

namespace InABox.Core
{
    // When creating a new field with properties, make sure to override LoadProperties() and SaveProperties()
    public abstract class DFLayoutFieldProperties : DFLayoutObject
    {
        [EditorSequence(-999)]
        [CodeEditor(Editable = Editable.Enabled, ValidChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_0123456789")]
        public string Code { get; set; }

        [EditorSequence(-998)]
        [TextBoxEditor]
        public string Description { get; set; }

        [EditorSequence(-997)]
        [ComboLookupEditor(typeof(PropertyLookupGenerator))]
        public string Property { get; set; }

        [CheckBoxEditor]
        [EditorSequence(4)]
        public bool Required { get; set; }

        [CheckBoxEditor]
        [EditorSequence(5)]
        public bool Secure { get; set; }

        [CheckBoxEditor]
        [EditorSequence(6)]
        public bool Retain { get; set; }

        [ExpressionEditor(null)]
        [EditorSequence(7)]
        public string Expression { get; set; }

        /// <summary>
        /// An expression that sets the field to have a background colour of its result.
        /// The result of the expression should be either a hex code like #rrggbb or #aarrggbb, or the string name of a <see cref="System.Drawing.KnownColor"/>,
        /// like 'Yellow'.
        /// </summary>
        [ExpressionEditor(null, ToolTip = "Evalutes to either a hex code (#RRGGBB or #AARRGGBB) or a colour name (like 'Red' or 'Yellow'), which sets the background colour for this variable.")]
        [EditorSequence(7)]
        public string ColourExpression { get; set; }

        public abstract object? ParseValue(object? value);

        public abstract string FormatValue(object? value);

        public virtual IEnumerable<CoreColumn> GetAdditionalColumns()
        {
            return Enumerable.Empty<CoreColumn>();
        }

        protected override void LoadProperties()
        {
            Description = GetProperty("Description", "");
            Property = GetProperty("Property", "");
            Required = GetProperty("Required", false);
            Secure = GetProperty("Secure", false);
            Retain = GetProperty("Retain", false);
            Expression = GetProperty("Expression", "");
            ColourExpression = GetProperty("ColourExpression", "");
        }

        protected override void SaveProperties()
        {
            SetProperty("Description", Description);
            SetProperty("Property", Property);
            SetProperty("Required", Required);
            SetProperty("Secure", Secure);
            SetProperty("Retain", Retain);
            SetProperty("Expression", Expression);
            SetProperty("ColourExpression", ColourExpression);
        }

        private class PropertyLookupGenerator : LookupGenerator<object>
        {
            public PropertyLookupGenerator(object[] items) : base(items)
            {
            }

            protected override void DoGenerateLookups()
            {
                var form = Items?.FirstOrDefault() as DigitalForm;
                if (form != null)
                {
                    var type = CoreUtils.TypeList(
                        AppDomain.CurrentDomain.GetAssemblies(),
                        x => string.Equals(x.Name, form.AppliesTo)
                    ).FirstOrDefault();
                    if (type != null)
                    {
                        var props = CoreUtils.PropertyList(type, x => true, true);
                        foreach (var prop in props.Keys)
                        {
                            var info = CoreUtils.GetProperty(type, prop);
                            var editor = info.GetEditor();
                            if (editor != null && editor.Editable == Editable.Enabled)
                            {
                                var bOK = true;
                                if (prop.Contains("."))
                                {
                                    var comps = prop.Split('.').Reverse().Skip(1).Reverse().ToList();
                                    while (comps.Count > 0)
                                    {
                                        var parent = string.Join(".", comps);
                                        comps.Remove(comps.Last());
                                        var parentinfo = CoreUtils.GetProperty(type, parent);
                                        var parenteditor = parentinfo.GetEditor();
                                        if (parenteditor is NullEditor)
                                            bOK = false;
                                    }
                                }

                                if (bOK)
                                    AddValue(prop, prop);
                            }
                        }
                    }
                }
            }
        }
    }

    public abstract class DFLayoutFieldProperties<T> : DFLayoutFieldProperties
    {
        public DFLayoutFieldProperties()
        {
            Default = default;
        }

        [EditorSequence(-995)]
        public T Default { get; set; }

        protected override void LoadProperties()
        {
            base.LoadProperties();
            Default = GetProperty("Default", default(T));
        }

        protected override void SaveProperties()
        {
            base.SaveProperties();
            SetProperty("Default", Default);
        }
    }
}