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

import java.util.Properties;
import java.util.Hashtable;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.naming.InitialContext;
import org.jboss.annotation.ejb.MessageProperties;
import org.jboss.aop.Dispatcher;
import org.jboss.aop.advice.Interceptor;
import org.jboss.aspects.remoting.Remoting;
import org.jboss.ejb3.Container;
import org.jboss.ejb3.ProxyFactory;
import org.jboss.ejb3.remoting.RemoteProxyFactory;
import org.jboss.naming.Util;

/**
 * comment
 *
 * @author <a href="mailto:bill@jboss.org">Bill Burke</a>
 */
public class RemoteProducerFactory extends ProducerFactory
{
   protected ConnectionFactory factory;

   public RemoteProducerFactory(Class producer, MessageProperties props, Destination dest, InitialContext ctx, Hashtable initialContextProperties)
   {
      super(producer, props, dest, ctx, initialContextProperties);
      try
      {
         String factoryName = pImpl.connectionFactory();
         if (factoryName.equals("")) factoryName = "ConnectionFactory";
         factory = (ConnectionFactory) ctx.lookup(factoryName);
      }
      catch (Exception e)
      {
         throw new RuntimeException(e);
      }
   }

   public void setContainer(Container container)
   {
   }

   public Object createProxy()
   {
      Class[] interfaces = {producer, ProducerObject.class};

      ProducerManagerImpl mImpl = null;

      mImpl = new ProducerManagerImpl(pImpl, dest, factory, props.delivery(), props.timeToLive(), props.priority(), methodMap, initialContextProperties);

      Interceptor[] interceptors = {mImpl};
      ProducerProxy ih = new ProducerProxy(mImpl, interceptors);
      return java.lang.reflect.Proxy.newProxyInstance(producer.getClassLoader(), interfaces, ih);
   }

   public void start() throws Exception
   {
      super.start();
      Class[] interfaces = {ProxyFactory.class};
      Object factoryProxy = Remoting.createPojiProxy(jndiName + PROXY_FACTORY_NAME, interfaces, RemoteProxyFactory.DEFAULT_CLIENT_BINDING);
      Util.rebind(ctx, jndiName + PROXY_FACTORY_NAME, factoryProxy);
      Dispatcher.singleton.registerTarget(jndiName + PROXY_FACTORY_NAME, this);
   }

   public void stop() throws Exception
   {
      super.stop();
      Util.unbind(ctx, jndiName + PROXY_FACTORY_NAME);
      Dispatcher.singleton.unregisterTarget(jndiName + PROXY_FACTORY_NAME);
   }
}
