using System;
using System.Diagnostics;
using System.Windows.Input;

namespace Microscopic_Traffic_Simulator
{
    /// <summary>
    /// Command class for binding UI commands with view models.
    /// </summary>
    class RelayCommand : ICommand
    {
        /// <summary>
        /// The execution logic for command.
        /// </summary>
        readonly Action<object> _execute;

        /// <summary>
        /// The execution status logic for command
        /// </summary>
        readonly Predicate<object> _canExecute;

        /// <summary>
        /// Creates a new command that can always execute.
        /// </summary>
        /// <param name="execute">The execution logic.</param>
        public RelayCommand(Action<object> execute) : this(execute, null) { }

        /// <summary>
        /// Creates a new command.
        /// </summary>
        /// <param name="execute">The execution logic.</param>
        /// <param name="canExecute">The execution status logic.</param>
        public RelayCommand(Action<object> execute, Predicate<object> canExecute)
        {
            if (execute == null)
                throw new ArgumentNullException("execute");

            _execute = execute;
            _canExecute = canExecute;
        }

        /// <summary>
        /// Method for getting if command is possible to run.
        /// </summary>
        /// <param name="parameter">Parameter of type object</param>
        /// <returns>True or False</returns>
        [DebuggerStepThrough]
        public bool CanExecute(object parameter)
        {
            return _canExecute == null ? true : _canExecute(parameter);
        }

        /// <summary>
        /// For connecting with Command Manager
        /// </summary>
        public event EventHandler CanExecuteChanged
        {
            add { CommandManager.RequerySuggested += value; }
            remove { CommandManager.RequerySuggested -= value; }
        }

        /// <summary>
        /// Execute action
        /// </summary>
        /// <param name="parameter">Parameter of action</param>
        public virtual void Execute(object parameter)
        {
            _execute(parameter);
        }
    }
}
