using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;

namespace Albatross.MVVM.Views {
	public class CommandReference : Freezable, ICommand {
		public const string Command_PN = "Command";

		public static readonly DependencyProperty CommandProperty =
			DependencyProperty.Register(Command_PN, typeof(ICommand), typeof(CommandReference),
			new PropertyMetadata(new PropertyChangedCallback(OnCommandChanged)));

		private static void OnCommandChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) {
			CommandReference commandReference = d as CommandReference;
			ICommand oldCommand = e.OldValue as ICommand;
			ICommand newCommand = e.NewValue as ICommand;

			if (oldCommand != null) { oldCommand.CanExecuteChanged -= commandReference.CanExecuteChangedHandler; }
			if (newCommand != null) { newCommand.CanExecuteChanged += commandReference.CanExecuteChangedHandler; }
		}

		public ICommand Command {
			get { return (ICommand)this.GetValue(CommandReference.CommandProperty); }
			set { this.SetValue(CommandReference.CommandProperty, value); }
		}

		public bool CanExecute(object parameter) {
			if (this.Command != null){
				return this.Command.CanExecute(parameter);
			}
			return false;
		}

		public void Execute(object parameter) {
			this.Command.Execute(parameter);
		}

		public event EventHandler CanExecuteChanged = (sender, args) => { };

		protected override Freezable CreateInstanceCore() {
			return new CommandReference();
		}

		void CanExecuteChangedHandler(object sender, EventArgs args) {
			CanExecuteChanged(sender, args);
		}
	}
}
