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

namespace InABox.DynamicGrid;

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

    public event PropertyChangedHandler? PropertyChanged;

    public string? SelectedProperty => SelectedItem as string;

    public PropertyNode(Expression expression)
    {
        SetResourceReference(StyleProperty, typeof(ComboBox));

        VerticalAlignment = System.Windows.VerticalAlignment.Stretch;
        VerticalContentAlignment = System.Windows.VerticalAlignment.Center;
        MinWidth = 100;

        var properties = CoreUtils.PropertyList(typeof(T), x => x.GetCustomAttribute<DoNotSerialize>() == null, true).Keys.ToList();
        properties.Sort();
        foreach (var property in properties)
        {
            Items.Add(property);
        }
        if (CoreUtils.TryFindMemberExpression(expression, out var mexp))
            SelectedItem = CoreUtils.GetFullPropertyName(mexp, ".");

        SelectionChanged += ComboBox_SelectionChanged;
    }

    public void Clear()
    {
        SelectedIndex = -1;
    }

    private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        var selected = SelectedItem as string;
        PropertyChanged?.Invoke(selected);
    }
}