/*
 * Asynchronous Engine .
 *
 * Copyright (C) 2004 Claude Hussenet
 * Contact : chussenet@yahoo.com
 *
 * Distributable under LGPL license.
 * See terms of license at gnu.org.
 */

package org.jboss.aspects.asynchronous.aspects.jboss;

import org.jboss.aop.annotation.AnnotationElement;
import org.jboss.aop.joinpoint.MethodInvocation;
import org.jboss.aspects.asynchronous.aspects.AsynchronousFacade;
import org.jboss.aspects.asynchronous.aspects.AsynchronousFacadeImpl;
import org.jboss.aspects.asynchronous.aspects.Utils;
import org.jboss.aspects.asynchronous.concurrent.ThreadManagerFactory;

/**
 * @author <a href="mailto:chussenet@yahoo.com">{Claude Hussenet Independent Consultant}</a>.
 * @version <tt>$Revision: 1.4.4.3 $</tt>
 */
public class AsynchronousAspect
{
   private AsynchronousInvokeTask asynchronousInvokeTask =
   new AsynchronousInvokeTask();

   public AsynchronousAspect() {}

   public Object execute(MethodInvocation invocation) throws Throwable
   {
      AsynchronousFacade asynchronousResult = null;
      if (invocation.getTargetObject() != null)
         asynchronousResult = (AsynchronousFacade) invocation.getTargetObject();
      else
      {
         Object[] tObject = invocation.getArguments();
         for (int i = 0; i < tObject.length; i++)
         {
            Object object = tObject[i];
            if (object instanceof AsynchronousFacade)
            {
               asynchronousResult = (AsynchronousFacade) object;
               break;
            }
         }
         if (asynchronousResult == null)
            asynchronousResult = new AsynchronousFacadeImpl();
      }
      Asynchronous asynchronous = (Asynchronous) AnnotationElement.getAnyAnnotation(invocation.getMethod(), Asynchronous.class);
      if (asynchronous!=null)
      {
      	if (asynchronousResult.getTimeout() == 0)
         asynchronousResult.setTimeout(asynchronous.timeout());

        if ((asynchronousResult.getId()!=null) && (asynchronousResult.getId().equals("None"))
       	                                       &&
       	              (asynchronous.id()!=null)&&(asynchronous.id().length()!=0) )
      	 asynchronousResult.setId(asynchronous.id());
	  }
      asynchronousResult.setAsynchronousTask(ThreadManagerFactory.getThreadManager().process(ThreadManagerFactory.createNewThreadManagerRequest(asynchronousResult.getId(),
      new InvokeTaskInputParameters((MethodInvocation) invocation.copy()),
      asynchronousInvokeTask,
      asynchronousResult.getTimeout())));
      Class returnType = invocation.getActualMethod().getReturnType();
      return Utils.returnInitObject(returnType);
   }
}
