using System;
using System.Windows.Input;

namespace SurfacePlot3D.Common
{
    public class RelayCommand<T> : ICommand
    {
        readonly Action<T> _targetExecuteMethod;

        readonly Func<T, Boolean> _targetCanExecuteMethod;

        public RelayCommand(Action<T> executeMethod)
        {
            _targetExecuteMethod = executeMethod;
        }

        public RelayCommand(Action<T> executeMethod, Func<T, Boolean> canExecuteMethod)
        {
            _targetExecuteMethod = executeMethod;
            _targetCanExecuteMethod = canExecuteMethod;
        }

        public void RaiseCanExecuteChanged()
        {
            CanExecuteChanged(this, System.EventArgs.Empty);
        }

        #region ICommand Members

        Boolean ICommand.CanExecute(Object parameter)
        {
            if (_targetCanExecuteMethod == null) return _targetExecuteMethod != null;
            T tparm = (T)parameter;

            return _targetCanExecuteMethod(tparm);
        }

        public event EventHandler CanExecuteChanged = delegate { };

        void ICommand.Execute(Object parameter)
        {
            _targetExecuteMethod?.Invoke((T)parameter);
        }

        #endregion
    }
}