using InABox.Clients;
using InABox.Core;
using NPOI.SS.Formula.Functions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
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, string>
    {
        private ComboBox Combo = null!; // late-initialising

        protected override FrameworkElement Create()
        {
            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);
                }

                var table = client.Query(
                    LookupFactory.DefineFilter(type),
                    columns,
                    LookupFactory.DefineSort(type)
                );
                var lookups = new Dictionary<Guid, ComboItemType>();
                foreach (var row in table.Rows)
                {
                    var id = row.Get<Guid>("ID");
                    var values = row.ToDictionary(new[] { "ID" });
                    var display = LookupFactory.FormatLookup(type, values, new 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) => ChangeField();
                //});

                //});
            }

            return Combo;
        }

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

        public override void SetEntityValue(object? value)
        {
            Combo.SelectedValue = value;
        }

        public override object? GetData(string dataField)
        {
            return ((KeyValuePair<Guid, ComboItemType>?)Combo.SelectedItem)?.Value.Item2.GetValueOrDefault(dataField);
        }
        public override Dictionary<string, object?>? GetAdditionalValues()
        {
            if (Field.Properties.AdditionalPropertiesList.Count == 0)
                return null;

            var values = new Dictionary<string, object?>();
            foreach(var field in Field.Properties.AdditionalPropertiesList)
            {
                values[field] = GetData(field);
            }
            return values;
        }

        public override string GetValue() => ((KeyValuePair<Guid, ComboItemType>?)Combo.SelectedItem)?.Value.Item1 ?? "";

        public override void SetValue(string? value)
        {
            var lookups = Combo.ItemsSource as Dictionary<Guid, ComboItemType>;
            if (lookups is null)
                return;
            var lookup = lookups!.FirstOrDefault(x => x.Value.Item1 == value);
            Combo.SelectedItem = lookup;
        }
        protected override bool IsEmpty() => Combo.SelectedValue == null || (Guid)Combo.SelectedValue == Guid.Empty;
    }
}
