using System;
using System.ComponentModel;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using InABox.Clients;
using InABox.Core;
using InABox.Wpf;

namespace InABox.DynamicGrid
{
    public interface IMultiSelectDialog
    {
        bool ShowDialog();
        Guid[] IDs();
        CoreTable Data();
    }

    public class MultiSelectDialog<T> : IMultiSelectDialog where T : Entity, IRemotable, IPersistent, new()
    {
        //private Expression<Func<T, object>>[] _columns = new Expression<Func<T, object>>[] { };
        private readonly Columns<T>? _columns;

        private readonly Filter<T>? _filter;
        private readonly DynamicDataGrid<T> datagrid;
        private readonly Grid grid;
        private readonly Button OKButton;
        private ThemableWindow? window;

        public MultiSelectDialog() : this(null, null)
        {
        }

        //public MultiSelectDialog(Filter<T> filter, Expression<Func<T, object>>[] columns, bool multiselect = true) : base()
        public MultiSelectDialog(Filter<T>? filter, Columns<T>? columns, bool multiselect = true)
        {
            _filter = filter;

            grid = new Grid();
            grid.Margin = new Thickness(5);
            grid.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1.0F, GridUnitType.Star) });
            grid.RowDefinitions.Add(new RowDefinition { Height = new GridLength(40.0F, GridUnitType.Pixel) });

            grid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1.0F, GridUnitType.Star) });
            grid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(80.0F, GridUnitType.Pixel) });
            grid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(80.0F, GridUnitType.Pixel) });

            datagrid = new DynamicDataGrid<T>();

            datagrid.Options.BeginUpdate();
            datagrid.Options.Clear();
            datagrid.Options.AddRange(DynamicGridOption.SelectColumns, DynamicGridOption.FilterRows);
            if (multiselect)
                datagrid.Options.Add(DynamicGridOption.MultiSelect);
            datagrid.Options.EndUpdate();

            datagrid.OnReload += Grid_OnReload;
            datagrid.OnDoubleClick += Grid_DoubleClick;
            datagrid.ColumnsTag = "MSD";
            if (columns != null)
            {
                _columns = columns;
                foreach (var column in columns.Items)
                    datagrid.AddHiddenColumn(column.Property);
                //datagrid.HiddenColumns.AddRange(columns);
            }
            else
            {
                var cols = LookupFactory.DefineColumns<T>()
                    .Default(ColumnType.IncludeOptional, ColumnType.IncludeForeignKeys, ColumnType.IncludeLinked);
                foreach (var col in cols.Items)
                    datagrid.AddHiddenColumn(col.ToString());
            }

            datagrid.SetValue(Grid.RowProperty, 0);
            datagrid.SetValue(Grid.ColumnProperty, 0);
            datagrid.SetValue(Grid.ColumnSpanProperty, 3);
            datagrid.OnSelectItem += Datagrid_OnSelectItem;
            grid.Children.Add(datagrid);

            OKButton = new Button();
            OKButton.Margin = new Thickness(5, 5, 0, 0);
            OKButton.Content = "OK";
            OKButton.Click += OKButton_Click;
            OKButton.SetValue(Grid.RowProperty, 1);
            OKButton.SetValue(Grid.ColumnProperty, 1);
            OKButton.IsEnabled = false;
            grid.Children.Add(OKButton);

            var CancelButton = new Button();
            CancelButton.Margin = new Thickness(5, 5, 0, 0);
            CancelButton.Content = "Cancel";
            CancelButton.Click += CancelButton_Click;
            CancelButton.SetValue(Grid.RowProperty, 1);
            CancelButton.SetValue(Grid.ColumnProperty, 2);
            grid.Children.Add(CancelButton);
        }

        public bool ShowDialog()
        {
            window = new ThemableWindow { Title = "Select Items", WindowStyle = WindowStyle.SingleBorderWindow };
            window.Content = grid;
            datagrid.Refresh(true, true);
            if (window.ShowDialog() == true)
                return true;
            return false;
        }

        public Guid[] IDs()
        {
            if (datagrid.Data != null && datagrid.SelectedRows.Any()) return datagrid.SelectedRows.Select(r => r.Get<T, Guid>(x => x.ID)).ToArray();
            return Array.Empty<Guid>();
        }

        public CoreTable Data()
        {
            var result = new CoreTable();
            result.Columns.Add(new CoreColumn { ColumnName = "ID", DataType = typeof(Guid) });

            //foreach (var column in _columns)
            //{
            //String name = CoreUtils.GetFullPropertyName(column, ".");
            //Type type = column.ReturnType;
            //result.Columns.Add(new CoreColumn() { ColumnName = name, DataType = type });

            //}
            foreach (var column in _columns.Items)
                result.Columns.Add(new CoreColumn { ColumnName = column.Property, DataType = column.ExpressionType() });

            if (datagrid.Data != null && datagrid.SelectedRows.Any())
                foreach (var sel in datagrid.SelectedRows)
                {
                    var row = result.NewRow();
                    foreach (var column in result.Columns)
                    {
                        var value = sel[column.ColumnName];
                        row.Set(column.ColumnName, value);
                    }

                    result.Rows.Add(row);
                }

            return result;
        }

        private void Grid_DoubleClick(object sender, HandledEventArgs args)
        {
            args.Handled = true;
            window!.DialogResult = true;
            window.Close();
        }

        private void Datagrid_OnSelectItem(object sender, DynamicGridSelectionEventArgs e)
        {
            OKButton.IsEnabled = e.Rows?.Any() == true;
        }

        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            window!.DialogResult = false;
            window.Close();
        }

        private void OKButton_Click(object sender, RoutedEventArgs e)
        {
            window!.DialogResult = true;
            window.Close();
        }

        public T[] Items(Columns<T>? columns = null)
        {
            if (datagrid.Data != null && datagrid.SelectedRows.Any())
            {
                Filter<T>? flt = null;
                foreach (var row in datagrid.SelectedRows)
                {
                    var id = row.Get<T, Guid>(x => x.ID);
                    flt = flt == null ? new Filter<T>(x => x.ID).IsEqualTo(id) : flt.Or(x => x.ID).IsEqualTo(id);
                }

                var items = new Client<T>().Query(flt, columns).Rows.Select(r => r.ToObject<T>());
                return items.ToArray();
            }

            return new T[] { };
        }

        private void Grid_OnReload(object sender, Filters<T> criteria, Columns<T> columns, ref SortOrder<T>? sortby)
        {
            if (_filter != null)
                criteria.Add(_filter);
        }
    }
}