/*
 * JBoss, the OpenSource J2EE webOS
 *
 * Distributable under LGPL license.
 * See terms of license at gnu.org.
 */

package org.jboss.ejb3.stateless;


import java.lang.reflect.Method;
import java.rmi.MarshalledObject;
import java.util.Hashtable;
import java.util.Map;
import javax.ejb.EJBException;
import javax.ejb.Timer;
import javax.ejb.TimerService;
import org.jboss.annotation.ejb.LocalBinding;
import org.jboss.annotation.ejb.RemoteBinding;
import org.jboss.annotation.ejb.RemoteBindings;
import org.jboss.aop.AspectManager;
import org.jboss.aop.MethodInfo;
import org.jboss.aop.advice.Interceptor;
import org.jboss.aop.joinpoint.Invocation;
import org.jboss.aop.joinpoint.InvocationResponse;
import org.jboss.aop.joinpoint.MethodInvocation;
import org.jboss.aop.util.MethodHashing;
import org.jboss.aspects.asynch.FutureHolder;
import org.jboss.ejb.AllowedOperationsAssociation;
import org.jboss.ejb.AllowedOperationsFlags;
import org.jboss.ejb.txtimer.TimedObjectInvoker;
import org.jboss.ejb3.EJBContainerInvocation;
import org.jboss.ejb3.EjbTimerUtil;
import org.jboss.ejb3.ProxyUtils;
import org.jboss.ejb3.SessionContainer;
import org.jboss.ejb3.callback.Callback;
import org.jboss.ejb3.remoting.IsLocalInterceptor;
import org.jboss.logging.Logger;
import org.jboss.proxy.ejb.handle.HomeHandleImpl;
import org.jboss.proxy.ejb.handle.StatelessHandleImpl;


/**
 * Comment
 *
 * @author <a href="mailto:bill@jboss.org">Bill Burke</a>
 * @version $Revision: 1.6.2.5 $
 */
public class StatelessContainer extends SessionContainer implements TimedObjectInvoker
{
   private static final Logger log = Logger.getLogger(StatelessContainer.class);

   protected TimerService timerService;

   public StatelessContainer(ClassLoader cl, String beanClassName, String ejbName, AspectManager manager, Hashtable ctxProperties)
   {
      super(cl, beanClassName, ejbName, manager, ctxProperties);
      beanContextClass = StatelessBeanContext.class;
   }

   public void start() throws Exception
   {
      super.start();
      timerService = EjbTimerUtil.getTimerService(this, this);
   }

   public void stop() throws Exception
   {
      EjbTimerUtil.removeTimerService(this);
      super.stop();
   }

   public TimerService getTimerService()
   {
      return timerService;
   }

   public void callTimeout(Timer timer) throws Exception
   {
      Callback cb = callbackHandler.getTimeoutCallback();
      if (cb == null) throw new EJBException("No method has been annotated with @Timeout");
      Object[] args = {timer};
      ClassLoader oldLoader = Thread.currentThread().getContextClassLoader();
      try
      {
         AllowedOperationsAssociation.pushInMethodFlag(AllowedOperationsFlags.IN_EJB_TIMEOUT);
         try
         {
            MethodInfo info = (MethodInfo) methodInterceptors.get(cb.getCallbackMethodHash());
            Interceptor[] aspects = info.interceptors;
            EJBContainerInvocation nextInvocation = new EJBContainerInvocation(info, aspects);
            nextInvocation.setAdvisor(this);
            nextInvocation.setArguments(args);
            nextInvocation.invokeNext();
         }
         catch (Throwable throwable)
         {
            if (throwable instanceof Exception) throw (Exception) throwable;
            throw new RuntimeException(throwable);
         }
         finally
         {
            AllowedOperationsAssociation.popInMethodFlag();
         }
      }
      finally
      {
         Thread.currentThread().setContextClassLoader(oldLoader);
      }
   }

   /**
    * Performs a synchronous local invocation
    */
   public Object localInvoke(Method method, Object[] args) throws Throwable
   {
      return localInvoke(method, args, null);
   }

   /**
    * Performs a synchronous or asynchronous local invocation
    *
    * @param provider If null a synchronous invocation, otherwise an asynchronous
    */
   public Object localInvoke(Method method, Object[] args, FutureHolder provider) throws Throwable
   {
      ClassLoader oldLoader = Thread.currentThread().getContextClassLoader();
      try
      {
         long hash = MethodHashing.calculateHash(method);
         MethodInfo info = (MethodInfo) methodInterceptors.get(hash);
         if (info == null)
         {
            throw new RuntimeException("Could not resolve beanClass method from proxy call: " + method.toString());
         }

         if (info.unadvisedMethod != null && isHomeMethod(info.unadvisedMethod))
         {
            return invokeLocalHomeMethod(info, args);
         }

         Interceptor[] aspects = info.interceptors;
         EJBContainerInvocation nextInvocation = new EJBContainerInvocation(info, aspects);
         nextInvocation.setAdvisor(this);
         nextInvocation.setArguments(args);

         ProxyUtils.addLocalAsynchronousInfo(nextInvocation, provider);
         return nextInvocation.invokeNext();
      }
      finally
      {
         Thread.currentThread().setContextClassLoader(oldLoader);
      }
   }

   public InvocationResponse dynamicInvoke(Object target, Invocation invocation) throws Throwable
   {
      ClassLoader oldLoader = Thread.currentThread().getContextClassLoader();
      try
      {
         Thread.currentThread().setContextClassLoader(classloader);
         MethodInvocation si = (MethodInvocation) invocation;
         MethodInfo info = (MethodInfo) methodInterceptors.get(si.getMethodHash());
         if (info == null)
         {
            throw new RuntimeException("Could not resolve beanClass method from proxy call");
         }

         Map responseContext = null;
         Object rtn = null;
         if (info.unadvisedMethod != null && isHomeMethod(info.unadvisedMethod))
         {
            rtn = invokeHomeMethod(info, si);
         }
         else if (info != null && info.unadvisedMethod != null && isEJBObjectMethod(info.unadvisedMethod))
         {
            rtn = invokeEJBObjectMethod(info, si);
         }
         else
         {

            EJBContainerInvocation newSi = null;
            Interceptor[] aspects = info.interceptors;

            newSi = new EJBContainerInvocation(info, aspects);
            newSi.setArguments(si.getArguments());
            newSi.setMetaData(si.getMetaData());
            newSi.setAdvisor(this);
            rtn = newSi.invokeNext();
            responseContext = newSi.getResponseContextInfo();
         }

         InvocationResponse response = new InvocationResponse(rtn);
         response.setContextInfo(responseContext);

         // marshall return value
         if (invocation.getMetaData().hasTag(IsLocalInterceptor.IS_LOCAL))
         {
            response = (InvocationResponse)new MarshalledObject(response).get();
         }
         return response;
      }
      finally
      {
         Thread.currentThread().setContextClassLoader(oldLoader);
      }

   }

   protected Object invokeEJBObjectMethod(MethodInfo info, MethodInvocation invocation) throws Throwable
   {
      if (info.unadvisedMethod.getName().equals("getHandle"))
      {
         StatelessHandleImpl handle = null;
         RemoteBinding remoteBindingAnnotation = (RemoteBinding) resolveAnnotation(RemoteBinding.class);
         if (remoteBindingAnnotation != null)
            handle = new StatelessHandleImpl(remoteBindingAnnotation.jndiBinding());

         return handle;
      }
      else if (info.unadvisedMethod.getName().equals("remove"))
      {
         return null;
      }
      else if (info.unadvisedMethod.getName().equals("getEJBHome"))
      {
         HomeHandleImpl homeHandle = null;

         RemoteBinding remoteBindingAnnotation = (RemoteBinding) resolveAnnotation(RemoteBinding.class);
         if (remoteBindingAnnotation != null)
            homeHandle = new HomeHandleImpl(remoteBindingAnnotation.jndiBinding());

         return homeHandle.getEJBHome();
      }
      else if (info.unadvisedMethod.getName().equals("getPrimaryKey"))
      {
         return null;
      }
      else if (info.unadvisedMethod.getName().equals("isIdentical"))
      {
         return false;
      }
      else
      {
         return null;
      }
   }

   private Object invokeLocalHomeMethod(MethodInfo info, Object[] args) throws Exception
   {
      if (info.unadvisedMethod.getName().equals("create"))
      {
         LocalBinding binding = (LocalBinding) resolveAnnotation(LocalBinding.class);

         StatelessLocalProxyFactory factory = new StatelessLocalProxyFactory();
         factory.setContainer(this);
         factory.init();

         Object proxy = factory.createProxy();

         return proxy;
      }
      else // remove
      {
         return null;
      }
   }

   protected Object invokeHomeMethod(MethodInfo info, MethodInvocation invocation) throws Throwable
   {
      if (info.unadvisedMethod.getName().equals("create"))
      {
         RemoteBinding binding = null;

         RemoteBindings bindings = (RemoteBindings) resolveAnnotation(RemoteBindings.class);
         if (bindings != null)
            binding = bindings.value()[0];
         else
            binding = (RemoteBinding) resolveAnnotation(RemoteBinding.class);

         StatelessRemoteProxyFactory factory = new StatelessRemoteProxyFactory();
         factory.setContainer(this);
         factory.setRemoteBinding(binding);
         factory.init();

         return factory.createProxy();
      }
      else // remove
      {
         return null;
      }
   }
}
