using System;
using System.Windows.Input;

namespace Crysome.Server.ViewModel;

public class RelayCommand<T> : ICommand
{
	private readonly Action<T> _execute;

	private readonly Predicate<T> _canExecute;

	public event EventHandler CanExecuteChanged
	{
		add
		{
			CommandManager.RequerySuggested += value;
		}
		remove
		{
			CommandManager.RequerySuggested -= value;
		}
	}

	public RelayCommand(Action<T> execute)
		: this(execute, (Predicate<T>)null)
	{
	}

	public RelayCommand(Action<T> execute, Predicate<T> canExecute)
	{
		_execute = execute ?? throw new ArgumentNullException("execute");
		_canExecute = canExecute;
	}

	public bool CanExecute(object parameter)
	{
		if (_canExecute != null)
		{
			return _canExecute((T)parameter);
		}
		return true;
	}

	public void Execute(object parameter)
	{
		_execute((T)parameter);
	}
}
