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

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Hashtable;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;
import org.jboss.ejb3.EJB3Util;
import org.jboss.ejb3.Ejb3Deployment;
import org.jboss.ejb3.entity.InjectedEntityManagerFactory;
import org.jboss.ejb3.entity.InjectedSessionFactory;

/**
 * Comment
 *
 * @author <a href="mailto:bill@jboss.org">Bill Burke</a>
 * @version $Revision: 1.2.2.3 $
 */
public class PersistenceUnitInjector implements PojoInjector
{
   private Hashtable initialContextProperties;

   public PersistenceUnitInjector(Hashtable initialContextProperties)
   {
      this.initialContextProperties = initialContextProperties;
   }

   public Object getEntityManagerFactory(PersistenceUnit ref, Class type)
           throws NamingException
   {
      EntityManagerFactory factory;
      if (ref.unitName() == null || ref.unitName().equals(""))
      {
         throw new RuntimeException("You must specify a unit name for @PersistenceUnit");
      }
      else
      {
         InitialContext ctx = EJB3Util.getInitialContext(initialContextProperties);
         factory = (EntityManagerFactory) ctx.lookup(Ejb3Deployment.ACTUAL_ENTITY_MANAGER_FACTORY_CONTEXT + "/" + ref.unitName());
         if (type.equals(EntityManagerFactory.class))
         {
         return new InjectedEntityManagerFactory(factory, Ejb3Deployment.ACTUAL_ENTITY_MANAGER_FACTORY_CONTEXT + "/" + ref.unitName(), initialContextProperties);
         }
         else
         {
            return new InjectedSessionFactory(factory, Ejb3Deployment.ACTUAL_ENTITY_MANAGER_FACTORY_CONTEXT + "/" + ref.unitName(), initialContextProperties);

         }
      }
   }

   public void inject(Method m, Annotation annotation, Object pojo)
   {
      InjectionHelper.checkMethodSignature(m, annotation);
      PersistenceUnit pu = (PersistenceUnit)annotation;
      try
      {
         Object factory = getEntityManagerFactory(pu, m.getParameterTypes()[0]);
         m.invoke(pojo, factory);
      }
      catch (Exception e)
      {
         throw new RuntimeException(e);
      }
   }

   public void inject(Field f, Annotation annotation, Object pojo)
   {
      PersistenceUnit pu = (PersistenceUnit)annotation;
      try
      {
         Object factory = getEntityManagerFactory(pu, f.getType());
         f.setAccessible(true);
         f.set(pojo, factory);
      }
      catch (Exception e)
      {
         throw new RuntimeException(e);
      }
   }

}
