using System;
using System.Collections.Generic;
using System.Linq;
using InABox.Clients;

namespace InABox.Core
{
    public abstract class DataLookupEditor : BaseEditor, ILookupEditor
    {
        public DataLookupEditor(Type type, params string[] othercolumns)
        {
            Type = type;

            Visible = Visible.Hidden;
            LookupWidth = int.MaxValue;

            var name = type.Name;

            OtherColumns = new Dictionary<string, string>();
            foreach (var othercolumn in othercolumns)
            {
                var map = othercolumn.Split('=');
                if (map.Length == 2)
                    OtherColumns[map.First()] = map.Last();
                else if (map.Length == 1)
                    OtherColumns[map.First()] = map.First();
            }
        }

        public Dictionary<string, string> OtherColumns { get; }

        /// <summary>
        /// The type of the parent entity; this is set by <see cref="DatabaseSchema"/>.
        /// </summary>
        public Type ParentType { get; set; }

        public Type Type { get; }

        public int LookupWidth { get; set; }

        public EditorButton[]? Buttons { get; set; }

        public virtual CoreTable Values(string columnname, BaseObject[]? items)
        {
            var client = ClientFactory.CreateClient(Type);

            var filter = LookupFactory.DefineLookupFilter(ParentType, Type, columnname, items ?? (Array.CreateInstance(ParentType, 0) as BaseObject[])!);
            var columns = LookupFactory.DefineLookupColumns(ParentType, Type, columnname);

            foreach (var key in OtherColumns.Keys)
                columns.Add(key);

            var sort = LookupFactory.DefineSort(Type);
            var result = client.Query(filter, columns, sort);

            result.Columns.Add(new CoreColumn { ColumnName = "Display", DataType = typeof(string) });
            foreach (var row in result.Rows)
            {
                row["Display"] = LookupFactory.FormatLookup(ParentType, Type, row, columnname);
            }

            return result;
        }

        public void Clear()
        {
        }

        protected BaseEditor CloneDataLookupEditor()
        {
            var result = (Activator.CreateInstance(GetType(), Type) as DataLookupEditor)!;
            foreach (var key in OtherColumns.Keys)
                result.OtherColumns[key] = OtherColumns[key];
            result.LookupWidth = LookupWidth;
            result.ParentType = ParentType;
            return result;
        }
    }
}