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<DynamicGridFilter>
    {
        public DynamicGridFilters Filters;
        private Type FilterType;

        public DynamicGridFilterGrid(Type filterType)
        {
            Filters = new DynamicGridFilters();
            Options.AddRange(DynamicGridOption.RecordCount,
                DynamicGridOption.AddRows, DynamicGridOption.EditRows, DynamicGridOption.DeleteRows,
                DynamicGridOption.MultiSelect);
            FilterType = filterType;

            OnCustomiseEditor += DynamicGridFilterGrid_OnCustomiseEditor;
        }

        private void DynamicGridFilterGrid_OnCustomiseEditor(IDynamicEditorForm sender, DynamicGridFilter[]? items, DynamicGridColumn column, BaseEditor editor)
        {
            if(column.ColumnName == nameof(DynamicGridFilter.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 DynamicGridFilter LoadItem(CoreRow row)
        {
            var index = Data.Rows.IndexOf(row);
            return Filters[index];
        }

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

        protected override void SaveItem(DynamicGridFilter item)
        {
            if (!Filters.Contains(item))
                Filters.Add(item);
        }
    }
}
