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

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Hashtable;
import javax.jms.Destination;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.Name;
import javax.naming.RefAddr;
import javax.naming.Reference;
import javax.naming.StringRefAddr;
import org.jboss.annotation.ejb.MessageProperties;
import org.jboss.annotation.ejb.MessagePropertiesImpl;
import org.jboss.annotation.ejb.Producer;
import org.jboss.aop.util.MethodHashing;
import org.jboss.ejb3.Container;
import org.jboss.ejb3.JndiProxyFactory;
import org.jboss.ejb3.ProxyFactory;
import org.jboss.naming.Util;

/**
 * comment
 *
 * @author <a href="mailto:bill@jboss.org">Bill Burke</a>
 */
public abstract class ProducerFactory implements ProxyFactory
{
   protected Class producer;
   protected MessageProperties props;
   protected Destination dest;
   protected HashMap<Long, MessageProperties> methodMap;
   protected ProducerImpl pImpl;
   protected String jndiName;
   protected InitialContext ctx;
   protected Hashtable initialContextProperties;

   public static final String PROXY_FACTORY_NAME = "PRODUCER_FACTORY";


   protected ProducerFactory(Class producer, MessageProperties props, Destination dest, InitialContext ctx, Hashtable ctxProperties)
   {
      this.producer = producer;
      this.props = props;
      this.dest = dest;
      this.ctx = ctx;
      this.initialContextProperties = ctxProperties;


      methodMap = new HashMap<Long, MessageProperties>();
      for (Method method : producer.getMethods())
      {
         MessageProperties mProps = method.getAnnotation(MessageProperties.class);
         if (mProps != null)
         {
            try
            {
               methodMap.put(MethodHashing.methodHash(method), new MessagePropertiesImpl(mProps));
            }
            catch (Exception e)
            {
               throw new RuntimeException(e);
            }
         }
      }
      Producer p = (Producer) producer.getAnnotation(Producer.class);
      pImpl = new ProducerImpl(p);
      jndiName = producer.getName();

   }

   public void setContainer(Container container)
   {
   }

   public void start() throws Exception
   {
      Context baseCtx = ctx;
      Name name = baseCtx.getNameParser("").parse(jndiName);
      baseCtx = Util.createSubcontext(baseCtx, name.getPrefix(name.size() - 1));
      String atom = name.get(name.size() - 1);
      RefAddr refAddr = new StringRefAddr(JndiProxyFactory.FACTORY, atom + PROXY_FACTORY_NAME);
      Reference ref = new Reference("java.lang.Object", refAddr, JndiProxyFactory.class.getName(), null);
      Util.rebind(baseCtx, atom, ref);
   }

   public void stop() throws Exception
   {
      Util.unbind(ctx, jndiName);
   }
}
