/*
 * JBoss, the OpenSource J2EE webOS
 * 
 * Distributable under LGPL license.
 * See terms of license at gnu.org.
 */
package org.jboss.aop.patterns.observable;

import org.jboss.aop.advice.Interceptor;
import org.jboss.aop.joinpoint.FieldInvocation;
import org.jboss.aop.joinpoint.Invocation;

/**
 * A Subject Interceptor. Traps changes to the object
 * and fires change notifications.
 * 
 * @author <a href="adrian@jboss.com">Adrian Brock</a>
 * @version $Revision: 1.1 $
 */
public class SubjectInterceptor implements Interceptor
{
   public String getName()
   {
      return "Observerable";
   }

   public Object invoke(Invocation invocation) throws Throwable
   {
      FieldInvocation fi = (FieldInvocation) invocation;
      Object before = fi.field.get(fi.targetObject);
      Object result = invocation.invokeNext();
      Object after = fi.field.get(fi.targetObject);

      // If it changed fire notifications
      if (before == null && after != null || before.equals(after) == false)
      {
         Subject observable = (Subject) fi.targetObject;
         observable.notifyObservers();
      }
      return result;
   }
}