using System;
using System.Windows.Input;

namespace Tornado3_2026Election.Common;

public sealed class RelayCommand<T> : ICommand
{
    private readonly Action<T?> _execute;
    private readonly Func<T?, bool>? _canExecute;

    public RelayCommand(Action<T?> execute, Func<T?, bool>? canExecute = null)
    {
        _execute = execute;
        _canExecute = canExecute;
    }

    public event EventHandler? CanExecuteChanged;

    public bool CanExecute(object? parameter)
    {
        if (parameter is null)
        {
            return _canExecute?.Invoke(default) ?? true;
        }

        return parameter is T typedParameter && (_canExecute?.Invoke(typedParameter) ?? true);
    }

    public void Execute(object? parameter)
    {
        if (parameter is null)
        {
            _execute(default);
            return;
        }

        if (parameter is T typedParameter)
        {
            _execute(typedParameter);
        }
    }

    public void NotifyCanExecuteChanged() => UiDispatcher.Enqueue(() => CanExecuteChanged?.Invoke(this, EventArgs.Empty));
}
