using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Windows.Controls;
using System.Windows.Media;
using InABox.Core;
using InABox.WPF;

namespace InABox.DynamicGrid;

public class PropertyNode<T> : Button
{
    public delegate void PropertyChangedHandler(string? property);

    public event PropertyChangedHandler? PropertyChanged;

    private string? _selectedProperty;
    public string? SelectedProperty
    {
        get => _selectedProperty;
        set
        {
            _selectedProperty = value;
            Content = _selectedProperty;
        }
    }

    private readonly string[] ColumnNames;

    public PropertyNode(string property)
    {
        VerticalAlignment = System.Windows.VerticalAlignment.Stretch;
        VerticalContentAlignment = System.Windows.VerticalAlignment.Center;
        HorizontalContentAlignment = System.Windows.HorizontalAlignment.Left;
        MinWidth = 100;

        Padding = new System.Windows.Thickness(5, 0, 5, 0);
        Background = new LinearGradientBrush(new GradientStopCollection()
        {
            new(Color.FromRgb(0xF0, 0xF0, 0xF0), 0.0),
            new(Color.FromRgb(0xE5, 0xE5, 0xE5), 1.0),
        })
        {
            StartPoint = new(0, 0),
            EndPoint = new(0, 1),
        };
        BorderBrush = Color.FromRgb(0xAC, 0xAC, 0xAC).ToBrush();

        var properties = DatabaseSchema.Properties(typeof(T))
            .Where(x => x.IsSerializable)
            .Select(x => x.Name)
            .ToList();
        properties.Sort();
        ColumnNames = properties.ToArray();
        SelectedProperty = properties.Contains(property) ? property : null;

        Click += PropertyNode_Click;
    }

    private void PropertyNode_Click(object sender, System.Windows.RoutedEventArgs e)
    {
        if(DynamicGridColumnNameSelectorGrid.SelectColumnName(typeof(T), ColumnNames, out var value))
        {
            SelectedProperty = value;
            PropertyChanged?.Invoke(value);
        }
    }

    public void Clear()
    {
        SelectedProperty = null;
    }
}