using InABox.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace InABox.DynamicGrid
{
    public class DynamicGridFilterGrid : DynamicGrid<CoreFilterDefinition>
    {
        public CoreFilterDefinitions Filters;
        private Type FilterType;

        public DynamicGridFilterGrid(Type filterType)
        {
            Filters = new CoreFilterDefinitions();
            FilterType = filterType;

            OnCustomiseEditor += DynamicGridFilterGrid_OnCustomiseEditor;
        }

        protected override void Init()
        {
        }

        protected override void DoReconfigure(FluentList<DynamicGridOption> options)
        {
            options.AddRange(DynamicGridOption.RecordCount,
                DynamicGridOption.AddRows, DynamicGridOption.EditRows, DynamicGridOption.DeleteRows,
                DynamicGridOption.MultiSelect);
        }

        private void DynamicGridFilterGrid_OnCustomiseEditor(IDynamicEditorForm sender, CoreFilterDefinition[]? items, DynamicGridColumn column, BaseEditor editor)
        {
            if(column.ColumnName == nameof(CoreFilterDefinition.Filter) && editor is FilterEditor filterEditor)
            {
                filterEditor.Type = FilterType;
            }
        }

        protected override void DeleteItems(params CoreRow[] rows)
        {
            foreach (var row in rows.OrderByDescending(x => x.Index))
                Filters.RemoveAt(row.Index);
        }

        protected override CoreFilterDefinition LoadItem(CoreRow row)
        {
            var index = Data.Rows.IndexOf(row);
            return Filters[index];
        }

        protected override void Reload(Filters<CoreFilterDefinition> criteria, Columns<CoreFilterDefinition> columns, ref SortOrder<CoreFilterDefinition>? sort, Action<CoreTable?, Exception?> action)
        {
            var result = new CoreTable();
            if (columns == null || !columns.Items.Any())
                result.LoadColumns(typeof(CoreFilterDefinition));
            else
                foreach (var column in columns.Items)
                    result.Columns.Add(new CoreColumn { ColumnName = column.Property, DataType = column.Expression.Type });
            result.LoadRows(Filters);
            action.Invoke(result, null);
        }

        public override void SaveItem(CoreFilterDefinition item)
        {
            if (!Filters.Contains(item))
            {
                Filters.Add(item);
            }
            Filters.Sort((x, y) => x.Sequence.CompareTo(y.Sequence));
        }
    }
}
