/*
 * 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 javax.annotation.Resource;
import javax.ejb.TimerService;
import javax.naming.NamingException;
import javax.transaction.UserTransaction;
import org.jboss.ejb3.Container;
import org.jboss.ejb3.tx.UserTransactionImpl;

/**
 * Comment
 *
 * @author <a href="mailto:bill@jboss.org">Bill Burke</a>
 * @version $Revision: 1.1.2.3 $
 */
public class ResourceInjector implements PojoInjector
{
   private Container container;

   public ResourceInjector(Container container)
   {
      this.container = container;
   }

   public void inject(Method m, Annotation annotation, Object pojo)
   {
      InjectionHelper.checkMethodSignature(m, annotation);
      Resource ref = (Resource)annotation;
      Object obj = null;
      obj = getResource(m.getParameterTypes()[0], m.getName().substring(3), ref);

      try
      {
         m.invoke(pojo, obj);
      }
      catch (Exception e)
      {
         throw new RuntimeException(e);
      }
   }

   private Object getResource(Class type, String defaultEncName, Resource ref)
   {
      Object obj;
      if (!ref.type().equals(Object.class))
      {
         type = ref.type();
      }
      String encName = ref.name();
      if (encName == null || encName.equals(""))
      {
         encName = defaultEncName;
      }
      if (type.equals(UserTransaction.class))
      {
         obj = new UserTransactionImpl();
      }
      else if (type.equals(TimerService.class))
      {
         obj = container.getTimerService();
      }
      else
      {
         String jndiName = ref.name();
         if (jndiName == null || jndiName.equals(""))
         {
            jndiName = defaultEncName;
         }
         try
         {
            obj = container.getInitialContext().lookup(jndiName);
         }
         catch (NamingException e)
         {
            jndiName = "java:/" + jndiName;
            try
            {
               obj = container.getInitialContext().lookup(jndiName);
            }
            catch (NamingException e1)
            {
               throw new RuntimeException(e1);
            }
         }
      }
      return obj;
   }

   public void inject(Field f, Annotation annotation, Object pojo)
   {
      Resource ref = (Resource)annotation;
      Object obj = getResource(f.getType(), f.getName(), ref);
      try
      {
         f.setAccessible(true);
         f.set(pojo, obj);
      }
      catch (Exception e)
      {
         throw new RuntimeException(e);
      }
   }

}
