﻿using System;
using Microsoft.Practices.Unity.InterceptionExtension;
using Utils.EnterpriseLibrary.AOP.Interfaces;
using Utils.EnterpriseLibrary.Logging;

namespace Utils.EnterpriseLibrary.AOP.CallHandlers
{
	/// <summary>
	/// This class handler is used in conjunction with Unity to handle INotifiyPropertyChanged
	/// implementations as an aspect.
	/// </summary>
	public class NotifyPropertyChangedCallHandler : CallHandlerBase
	{
		public override IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
		{

			// If the class doesn't implement INotify continue down the interception chain
			if (!ShouldInvoke(input) || !(input.Target is INotify))
				return getNext().Invoke(input, getNext);

			Log.Debug(string.Format("Firing Notify (priority {2}) on {0} because of {1}", input.Target.GetType().BaseType.Name, input.MethodBase.Name, Order));
			var method = input.MethodBase;

			// Get the property name
			var propertyName = method.Name.Substring(4);

			var notifyClass = input.Target as INotify;

			notifyClass.FirePropertyChanging(propertyName);

			// call Next in the interception chain
			var results = getNext.Invoke().Invoke(input, getNext);

			notifyClass.FirePropertyChanged(propertyName);

			return results;
		}


		protected override void Invoke(IMethodInvocation input)
		{
			throw new NotImplementedException();
		}
	}
}
