using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using InABox.Core;
using InABox.Wpf;

namespace InABox.DynamicGrid;

public class FilterNodeGrid<T> : Grid
{
    private List<FilterNode<T>> Filters;
    private FilterEditorConfiguration Configuration;

    public FilterNodeType FilterType;

    public FilterNodeGrid(List<Filter<T>> filters, FilterNodeType filterType, FilterEditorConfiguration configuration)
    {
        Configuration = configuration;

        ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) });

        FilterType = filterType;

        Filters = new();
        changing = true;
        foreach (var filter in filters)
        {
            AddFilter(filter);
        }
        changing = false;

        RefreshGrid();
    }

    private bool changing = false;

    public void Clear()
    {
        foreach(var element in Filters)
        {
            Children.Remove(element);
        }
        Filters.Clear();
        RefreshGrid();
    }

    public void AddFilter(Filter<T> filter, bool open = false)
    {
        RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto });

        var element = new FilterNode<T>(filter, FilterType, configuration: Configuration)
        {
            Margin = new Thickness(0, 5, 0, 0)
        };
        element.Remove += () =>
        {
            Filters.Remove(element);
            Children.Remove(element);
            RefreshGrid();
        };
        element.SetValue(ColumnProperty, 0);

        Children.Add(element);
        Filters.Add(element);

        if (!changing)
            RefreshGrid();
    }

    public void RefreshGrid()
    {
        RowDefinitions.Clear();

        var row = 0;
        foreach(var element in Filters)
        {
            RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto });

            element.SetValue(RowProperty, row);

            row++;
        }
    }

    public List<Filter<T>> GetFilters()
    {
        return Filters.Select(x => x.GetFilter()).Where(x => x != null).Select(x => x!).ToList();
    }
}