using InABox.Clients;
using InABox.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using ComboItemType = System.Tuple<string, System.Collections.Generic.Dictionary<string, object?>>;

namespace InABox.DynamicGrid
{

    public class DFLookupControl : DynamicFormFieldControl<DFLayoutLookupField, DFLayoutLookupFieldProperties, Guid, DFLayoutLookupValue>
    {

        private DFLayoutLookupValue _value = null!;
        
        private ComboBox Combo = null!; // late-initialising
        
        protected override FrameworkElement Create()
        {
            _value = new DFLayoutLookupValue();
            Combo = new ComboBox();
            if (CoreUtils.TryGetEntity(Field.Properties.LookupType, out var type))
            {
                var client = ClientFactory.CreateClient(type);
                //Task.Run(() =>
                //{

                var columns = LookupFactory.DefineColumns(type);
                foreach(var property in Field.Properties.AdditionalPropertiesList)
                {
                    columns.Add(property);
                }

                IFilter? filter;
                if (!Field.Properties.Filter.IsNullOrWhiteSpace())
                {
                    filter = Serialization.Deserialize(typeof(Filter<>).MakeGenericType(type), Field.Properties.Filter) as IFilter;
                    filter?.ConvertCustomValues((_, value) =>
                    {
                        var property = System.Text.Encoding.UTF8.GetString(value.Data);
                        return FormDesignGrid.DataModel?.GetEntityValue(property);
                    });
                }
                else
                {
                    filter = LookupFactory.DefineFilter(type);
                }

                var table = client.Query(
                    filter,
                    columns,
                    LookupFactory.DefineSort(type)
                );
                var lookups = new Dictionary<Guid, ComboItemType>()
                {
                    { Guid.Empty, new("(None)", table.NewRow().ToDictionary(new[] { "ID" })) }
                };
                foreach (var row in table.Rows)
                {
                    var id = row.Get<Guid>("ID");
                    var values = row.ToDictionary(new[] { "ID" });
                    var display = LookupFactory.FormatLookup(type, values, Array.Empty<string>());
                    lookups[id] = new(display, values);
                }
                //Dispatcher.Invoke(() =>
                //{

                Combo.DisplayMemberPath = "Value.Item1";
                Combo.SelectedValuePath = "Key";
                Combo.ItemsSource = lookups;
                Combo.VerticalContentAlignment = VerticalAlignment.Center;
                Combo.SelectionChanged += (sender, e) =>
                {
                    var lookup = (KeyValuePair<Guid, ComboItemType>?)Combo.SelectedItem;

                    _value.ID = lookup?.Key ?? Guid.Empty;
                    _value.Text = _value.ID != Guid.Empty ? lookup?.Value.Item1 ?? "" : "";
                    _value.Values = lookup?.Value.Item2 ?? new Dictionary<string, object?>();

                    ChangeField();
                };
                //});

                //});
            }

            return Combo;
        }

        public override void SetSerializedValue(DFLayoutLookupValue value)
        {
            SetValue(value.ID);
        }

        public override DFLayoutLookupValue GetSerializedValue()
        {
            return _value;
        }

        public override object? GetEntityValue()
        {
            return (Guid?)Combo.SelectedValue ?? Guid.Empty;
        }

        public override object? GetData(string dataField)
        {
            return ((KeyValuePair<Guid, ComboItemType>?)Combo.SelectedItem)?.Value.Item2.GetValueOrDefault(dataField);
        }

        public override Guid GetValue() => ((KeyValuePair<Guid, ComboItemType>?)Combo.SelectedItem)?.Key ?? Guid.Empty;

        public override void SetValue(Guid value)
        {
            if (Combo.ItemsSource is not Dictionary<Guid, ComboItemType> lookups)
                return;
            var lookup = lookups!.FirstOrDefault(x => x.Key == value);
            Combo.SelectedItem = lookup;

            var combo = lookup.Value;

            _value.ID = lookup.Key;
            _value.Text = _value.ID != Guid.Empty ? combo?.Item1 ?? "" : "";
            _value.Values = combo?.Item2 ?? new Dictionary<string, object?>();
        }
        protected override bool IsEmpty() => Combo.SelectedValue == null || (Guid)Combo.SelectedValue == Guid.Empty;
    }
}
