using System.Windows.Input;

namespace GreadyPoang.Common;

public class LoadedBehavior
{
    public static readonly BindableProperty CommandProperty =
        BindableProperty.CreateAttached(
            "Command",
            typeof(ICommand),
            typeof(LoadedBehavior),
            null,
            propertyChanged: OnCommandChanged);

    public static ICommand GetCommand(BindableObject view) =>
        (ICommand)view.GetValue(CommandProperty);

    public static void SetCommand(BindableObject view, ICommand value) =>
        view.SetValue(CommandProperty, value);

    private static void OnCommandChanged(BindableObject bindable, object oldValue, object newValue)
    {
        if (bindable is VisualElement element && newValue is ICommand command)
        {
            element.Loaded += (s, e) =>
            {
                if (command.CanExecute(null))
                {
                    command.Execute(null);
                }
            };
        }
    }

}
