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

import java.lang.reflect.Method;
import org.jboss.aop.advice.Interceptor;
import org.jboss.aop.joinpoint.Invocation;
import org.jboss.ejb3.Container;
import org.jboss.ejb3.EJBContainerInvocation;
import org.jboss.ejb3.injection.pojo.InjectionHelper;

/**
 * Comment
 *
 * @author <a href="mailto:bill@jboss.org">Bill Burke</a>
 * @version $Revision: 1.1.6.3 $
 */
public class EJB3InterceptorsInterceptor implements Interceptor
{
   private Object[] interceptors;
   private Method[] aroundInvokes;
   private Method beanAroundInvoke;
   private volatile boolean initialized = false;

   public EJB3InterceptorsInterceptor(Object[] interceptors, Method[] aroundInvokes, Method beanAroundInvoke)
   {
      this.interceptors = interceptors;
      this.aroundInvokes = aroundInvokes;
      this.beanAroundInvoke = beanAroundInvoke;
   }

   public String getName()
   {
      return getClass().getName();
   }

   public Object invoke(Invocation invocation) throws Throwable
   {
      EJBContainerInvocation inv = (EJBContainerInvocation) invocation;
      if (!initialized)
      {
         synchronized (this) {
            if (!initialized) // double check but I don't care.
            {
               initialized = true;
               for (Object interceptor : interceptors)
               {
                  try
                  {
                     InjectionHelper.iterateHardcodedInjectors((Container) inv.getAdvisor(), interceptor);
                  }
                  catch (Exception e)
                  {
                     throw new RuntimeException("Unable to injection into interceptor: " + interceptor.getClass(), e);
                  }
               }
            }
         }
      }
      InvocationContextImpl ctx = new InvocationContextImpl(inv, interceptors, aroundInvokes, beanAroundInvoke);
      return ctx.proceed();
   }
}
