/*
 * JBoss, the OpenSource EJB server
 *
 * Distributable under LGPL license.
 * See terms of license at gnu.org.
 */
package org.jboss.ejb3.service;

import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import org.jboss.aspects.asynch.AsynchMixin;
import org.jboss.aspects.asynch.AsynchProvider;
import org.jboss.aspects.asynch.FutureHolder;
import org.jboss.ejb3.Container;
import org.jboss.ejb3.JBossProxy;
import org.jboss.ejb3.LocalProxy;
import org.jboss.ejb3.ProxyUtils;

/**
 * @author <a href="mailto:kabir.khan@jboss.org">Kabir Khan</a>
 * @version $Revision: 1.2.4.3 $
 */
public class ServiceLocalProxy extends LocalProxy
{
   AsynchProvider provider;

   protected ServiceLocalProxy()
   {
   }

   public ServiceLocalProxy(Container container)
   {
      super(container);
   }

   public ServiceLocalProxy(AsynchProvider provider, Container container)
   {
      super(container);
      this.provider = provider;
   }

   public Object invoke(Object proxy, Method method, Object[] args)
           throws Throwable
   {
      if (method.getDeclaringClass() == AsynchProvider.class)
      {
         return provider.getFuture();
      }

      Object ret = ProxyUtils.handleCallLocally((JBossProxy) proxy, this, method, args);
      if (ret != null)
      {
         return ret;
      }

      ServiceContainer sc = (ServiceContainer) container;
      return sc.localInvoke(method, args, (FutureHolder) provider);
   }

   public Object getAsynchronousProxy(Object proxy)
   {
      Class[] infs = proxy.getClass().getInterfaces();
      if (!ProxyUtils.isAsynchronous(infs))
      {
         Class[] interfaces = ProxyUtils.addAsynchProviderInterface(infs);
         AsynchMixin mixin = new AsynchMixin();
         ServiceLocalProxy handler = new ServiceLocalProxy(mixin, container);
         return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), interfaces, handler);
      }

      //I was already asynchronous
      return proxy;
   }


   public String toString()
   {
      return container.getEjbName().toString();
   }

}
