using System;
using System.Windows.Input;
using Siger.Middlelayer.License.ViewModels;

namespace Siger.Middlelayer.License
{
    public class ButtonCommand: BaseViewModel,ICommand
    {
        private readonly Action<object> _executeAction;
        private readonly Func<object, bool> _canExecuteFunc;

        public event EventHandler CanExecuteChanged;

        public ButtonCommand(Action<object> executeAction, string description = "", Func<object, bool> canExecuteFunc = null)
        {
            _executeAction = executeAction;
            _canExecuteFunc = canExecuteFunc;
            Description = description;
        }

        protected ButtonCommand(Action<object> executeAction, Func<object, bool> canExecuteFunc = null)
        {
            if (executeAction == null)
            {
                throw new NullReferenceException("Execute Action can not be null");
            }
            _executeAction = executeAction;
            _canExecuteFunc = canExecuteFunc;
        }

        /// <summary>
        /// If this command can executed
        /// </summary>
        /// <param name="parameter"></param>
        /// <returns></returns>
        public bool CanExecute(object parameter)
        {
            if (!IsEnabled)
            {
                return false;
            }

            if (_canExecuteFunc != null)
            {
                return _canExecuteFunc(parameter);
            }
            return true;
        }

        /// <summary>
        /// Execute the command
        /// </summary>
        /// <param name="parameter"></param>
        public void Execute(object parameter)
        {
            if (CanExecute(parameter))
            {
                _executeAction(parameter);
            }
        }

        public virtual void OnCanExecuteChanged()
        {
            if (CanExecuteChanged != null) CanExecuteChanged.Invoke(this, EventArgs.Empty);
        }
    }
}
