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

namespace InABox.DynamicGrid
{
    public class DynamicGridFilterGrid : DynamicItemsListGrid<CoreFilterDefinition>
    {
        private CoreFilterDefinitions _filters;
        public CoreFilterDefinitions Filters
        {
            get => _filters;
            [MemberNotNull(nameof(_filters))]
            set
            {
                _filters = value;
                Items = value;

                var globalCount = _filters.Count(x => !x.Private);
                var privateI = 0;
                var globalI = 0;
                foreach(var filter in _filters)
                {
                    if (filter.Private)
                    {
                        filter.Sequence = globalCount + privateI++;
                    }
                    else
                    {
                        filter.Sequence = globalI++;
                    }
                }
            }
        }

        private Type FilterType;

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

            OnCustomiseEditor += DynamicGridFilterGrid_OnCustomiseEditor;
        }

        protected override void DoReconfigure(DynamicGridOptions options)
        {
            base.DoReconfigure(options);

            options.RecordCount = true;
            options.AddRows = true;
            options.EditRows = true;
            options.DeleteRows = true;
            options.MultiSelect = true;
        }

        public override void SaveItem(CoreFilterDefinition item)
        {
            base.SaveItem(item);
        }

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