using InABox.Core;
using InABox.WPF;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
using System.Windows.Media.Imaging;

namespace InABox.DynamicGrid;

public class DynamicSelectorGrid<T> : DynamicDataGrid<T>
    where T : Entity, IRemotable, IPersistent, new()
{
    private static BitmapImage tick = InABox.Wpf.Resources.tick.AsBitmapImage();

    public HashSet<Guid> SelectedIDs { get; set; } = new();

    private HashSet<Guid> LastVisible = new();

    public delegate void SelectionChangedEvent(HashSet<Guid> selected);
    public event SelectionChangedEvent? SelectionChanged;

    public DynamicSelectorGrid(DynamicActionColumnPosition tickPosition)
    {
        ActionColumns.Add(new DynamicImageColumn(Selected_Image, Selected_Click)
        {
            Position = tickPosition
        });
    }

    private BitmapImage? Selected_Image(CoreRow? row)
    {
        if (row is null) return tick;

        return SelectedIDs.Contains(row.Get<T, Guid>(x => x.ID)) ? tick : null;
    }

    protected virtual Guid[] GetSelectedGuids(Guid id)
    {
        return new Guid[] { id };
    }

    protected IEnumerable<Guid> FilteredGuids
    {
        get
        {
            var predicates = GetFilterPredicates();
            return Data.Rows.Where(r =>
            {
                return predicates.All(x => x.Item2(r));
            }).Select(x => x.Get<T, Guid>(x => x.ID));
        }
    }

    protected override void DoFilterChanged()
    {
        base.DoFilterChanged();
        DoSelectionChanged();
    }

    private void DoSelectionChanged()
    {
        var ids = SelectedIDs.Intersect(FilteredGuids).ToHashSet();
        if(ids.Count != LastVisible.Count || ids.Any(x => !LastVisible.Contains(x)))
        {
            LastVisible = ids;
            SelectionChanged?.Invoke(LastVisible);
        }
    }

    private bool Selected_Click(CoreRow? row)
    {
        if (row is null)
        {
            var menu = new ContextMenu();
            menu.AddItem("Select All", null, SelectAll_Click);
            menu.AddItem("Deselect All", null, DeselectAll_Click);
            menu.IsOpen = true;
            return false;
        }

        var parent = row.Get<T, Guid>(x => x.ID);
        var ids = GetSelectedGuids(parent);
        if (SelectedIDs.Contains(parent))
        {
            foreach (var id in ids.Where(x => SelectedIDs.Contains(x)))
            {
                SelectedIDs.Remove(id);
                var update = Data.Rows.FirstOrDefault(r => r.Get<T, Guid>(x => x.ID) == id);
                if (update != null)
                    InvalidateRow(update);
            }
        }
        else
        {
            foreach (var id in ids.Where(x => !SelectedIDs.Contains(x)))
            {
                SelectedIDs.Add(id);
                var update = Data.Rows.FirstOrDefault(r => r.Get<T, Guid>(x => x.ID) == id);
                if (update != null)
                    InvalidateRow(update);
            }
        }

        DoSelectionChanged();

        InvalidateRow(row);
        return false;
    }

    private void DeselectAll_Click()
    {
        SelectedIDs.Clear();
        DoSelectionChanged();
        InvalidateGrid();
    }

    private void SelectAll_Click()
    {
        SelectedIDs = Data.Rows.Select(x => x.Get<T, Guid>(x => x.ID)).ToHashSet();
        DoSelectionChanged();
        InvalidateGrid();
    }

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