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

import java.io.Serializable;
import java.util.Hashtable;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceContextType;
import org.jboss.ejb3.EJB3Util;
import org.jboss.ejb3.EJBContainer;

/**
 * Comment
 *
 * @author <a href="mailto:bill@jboss.org">Bill Burke</a>
 * @version $Revision: 1.1.2.4 $
 */
public class InjectedEntityManagerFactory implements EntityManagerFactory, Serializable
{
   private transient EntityManagerFactory delegate;
   private String jndiName;
   private Hashtable initialContextProperties;

   public InjectedEntityManagerFactory(EntityManagerFactory delegate, String jndiName, Hashtable initialContextProperties)
   {
      this.delegate = delegate;
      this.jndiName = jndiName;
      this.initialContextProperties = initialContextProperties;
   }


   public InjectedEntityManagerFactory(EntityManagerFactory delegate, Hashtable initialContextProperties)
   {
      this(delegate, EJBContainer.ENC_CTX_NAME + "/" + EJBContainer.ENTITY_MANAGER_FACTORY, initialContextProperties);
   }

   private EntityManagerFactory getDelegate()
   {
      if (delegate == null)
      {
         try
         {
            InitialContext ctx = EJB3Util.getInitialContext(initialContextProperties);
            delegate = (EntityManagerFactory) ctx.lookup(jndiName);
         }
         catch (NamingException e)
         {
            throw new RuntimeException(e);
         }
      }
      return delegate;
   }

   public EntityManager createEntityManager()
   {
      return getDelegate().createEntityManager();
   }

   public EntityManager createEntityManager(PersistenceContextType type)
   {
      return getDelegate().createEntityManager(type);
   }

   public EntityManager getEntityManager()
   {
      return getDelegate().getEntityManager();
   }

   public void close()
   {
      throw new IllegalStateException("It is illegal to close an injected EntityManagerFactory");
   }

   public boolean isOpen()
   {
      return getDelegate().isOpen();
   }
}
