using InABox.Core;
using InABox.Wpf;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
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(DynamicGridOptions options)
        {
            options.RecordCount = true;
            options.AddRows = true;
            options.EditRows = true;
            options.DeleteRows = true;
            options.MultiSelect = true;
        }

        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;
            }
        }

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

        public 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, 
            CancellationToken token, Action<CoreTable?, Exception?> action)
        {
            var result = new CoreTable();
            if (columns == null || columns.Count == 0)
                result.LoadColumns(typeof(CoreFilterDefinition));
            else
                result.LoadColumns(columns);
            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));
        }
    }
}
