using System;
using System.Windows.Input;

namespace BindingMemoryLeak
{
    public class DelegateCommand : ICommand
    {
        public DelegateCommand(Action<object> execute)
        {
            if (execute == null)
            {
                throw new ArgumentNullException(nameof(execute));
            }

            m_execute = execute;
        }

        public DelegateCommand(Func<object, bool> canExecute, Action<object> execute)
        {
            if (canExecute == null)
            {
                throw new ArgumentNullException(nameof(canExecute));
            }
            if (execute == null)
            {
                throw new ArgumentNullException(nameof(execute));
            }

            m_canExecute = canExecute;
            m_execute = execute;
        }

        public event EventHandler CanExecuteChanged;

        public bool CanExecute(object parameter)
        {
            return m_canExecute == null || m_canExecute(parameter);
        }

        public void Execute(object parameter)
        {
            m_execute(parameter);
        }

        public void RaiseCanExecuteChanged()
        {
            var handler = CanExecuteChanged;
            if (handler != null)
            {
                handler(this, System.EventArgs.Empty);
            }
        }

        #region Private members
        private Func<object, bool> m_canExecute;
        private Action<object> m_execute;
        #endregion
    }
}