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

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import javax.naming.Context;
import org.jboss.annotation.ejb.Depends;
import org.jboss.aop.Advisor;
import org.jboss.ejb3.Container;
import org.jboss.ejb3.dd.EjbRef;
import org.jboss.ejb3.dd.EnterpriseBean;
import org.jboss.ejb3.dd.EnterpriseBeans;
import org.jboss.logging.Logger;
import javassist.bytecode.AnnotationsAttribute;
import javassist.bytecode.ClassFile;
import javassist.bytecode.annotation.Annotation;
import javassist.bytecode.annotation.ArrayMemberValue;
import javassist.bytecode.annotation.MemberValue;
import javassist.bytecode.annotation.StringMemberValue;

/**
 * @author <a href="mailto:kabir.khan@jboss.org">Kabir Khan</a>
 * @version $Revision: 1.4.2.4 $
 */
public class DependsHandler
{
   private static final Logger log = Logger.getLogger(DependsHandler.class);

   //TODO provide for dependencies/ejb-refs outside of current deployement descriptor
   public static Collection getAllDepends(Class ejbClass, EnterpriseBean ejb, EnterpriseBeans ejbs)
   {
      ArrayList depends = new ArrayList();
      Iterator ejbRefs = ejb.getEjbRefs().iterator();
      while (ejbRefs.hasNext())
      {
         String dependencyName = null;
         try
         {
            EjbRef ejbRef = (EjbRef) ejbRefs.next();
            String remote = ejbRef.getRemote();
            EnterpriseBean reference = ejbs.findEjbByRemote(remote);
            if (reference != null)
            {
               if (reference.getJndiName() != null)
                  remote = reference.getJndiName();
               else
                  remote = reference.getEjbClass();
            }
            dependencyName = "jboss.j2ee:service=EJB3,name=" + remote;
            ObjectName dependency = new ObjectName(dependencyName);
            depends.add(dependency);
         }
         catch (MalformedObjectNameException e)
         {
            throw new RuntimeException("'" + dependencyName + "' is not a valid object name");
         }
      }

      return depends;
   }

   public static Collection getAllDepends(ClassFile cf, AnnotationsAttribute visible)
   {
      ArrayList depends = null;

      //Get the class annotation
      Annotation info = visible.getAnnotation(org.jboss.annotation.ejb.Depends.class.getName());
      depends = getDependsValues(depends, info);

      //Get the method annotations
      for (Iterator methods = cf.getMethods().iterator(); methods.hasNext();)
      {
         javassist.bytecode.MethodInfo minfo = (javassist.bytecode.MethodInfo) methods.next();
         AnnotationsAttribute mgroup = (AnnotationsAttribute) minfo.getAttribute(AnnotationsAttribute.visibleTag);
         if (mgroup == null) continue;
         javassist.bytecode.annotation.Annotation binfo = mgroup.getAnnotation(Depends.class.getName());
         depends = getDependsValues(depends, binfo);
      }

      for (Iterator fields = cf.getFields().iterator(); fields.hasNext();)
      {
         javassist.bytecode.FieldInfo finfo = (javassist.bytecode.FieldInfo) fields.next();
         AnnotationsAttribute mgroup = (AnnotationsAttribute) finfo.getAttribute(AnnotationsAttribute.visibleTag);
         if (mgroup == null) continue;
         javassist.bytecode.annotation.Annotation binfo = mgroup.getAnnotation(Depends.class.getName());
         depends = getDependsValues(depends, binfo);
      }

      return depends;
   }

   private static ArrayList getDependsValues(ArrayList depends, Annotation info)
   {
      if (info == null) return depends;

      ArrayMemberValue amv = (ArrayMemberValue) info.getMemberValue("value");
      MemberValue[] values = amv.getValue();

      for (int i = 0; i < values.length; i++)
      {
         StringMemberValue sv = (StringMemberValue) values[i];
         try
         {
            ObjectName on = new ObjectName(sv.getValue());
            if (depends == null) depends = new ArrayList();
            depends.add(on);
         }
         catch (MalformedObjectNameException e)
         {
            throw new RuntimeException("'" + sv.getValue() + "' is not a valid object name");
         }
      }
      return depends;
   }


   private static void loadResourcesAnnotation(Container container, Context resourceCtx) throws Exception
   {
      Depends depends = (Depends) ((Advisor) container).resolveAnnotation(Depends.class);
      if (depends == null) return;
      for (String name : depends.value())
      {
         ObjectName objectName = new ObjectName(name);
      }
   }

   public static List loadInjectors(Container container) throws Exception
   {
      Class clazz = container.getBeanClass();
      Method[] methods = clazz.getMethods();
      ArrayList list = new ArrayList();
      for (int i = 0; i < methods.length; i++)
      {
         Depends dep = (Depends) ((Advisor) container).resolveAnnotation(methods[i], Depends.class);
         if (dep != null)
         {
            if (!methods[i].getName().startsWith("set")) throw new RuntimeException("@Depends can only be used with a set method: " + methods[i]);
            if (methods[i].getParameterTypes().length != 1) throw new RuntimeException("@Depends annotated setter methods can only take one parameter: " + methods[i]);

            String[] names = dep.value();
            if (names.length != 1) throw new RuntimeException("@Depends on a method can only take one object name: " + methods[i]);
            ObjectName on = new ObjectName(names[0]);
            list.add(new DependsMethodInjector(methods[i], on));
         }
      }
      loadFieldInjectors(clazz, container, list);
      return list;
   }

   private static void loadFieldInjectors(Class clazz, Container container, ArrayList list) throws Exception
   {
      if (clazz == null || clazz.equals(java.lang.Object.class)) return;
      loadFieldInjectors(clazz.getSuperclass(), container, list);
      Field[] fields = clazz.getDeclaredFields();
      for (int i = 0; i < fields.length; i++)
      {
         Depends dep = (Depends) ((Advisor) container).resolveAnnotation(fields[i], Depends.class);
         if (dep != null)
         {
            String[] names = dep.value();
            if (names.length != 1) throw new RuntimeException("@Depends on a field can only take one object name: " + fields[i]);
            ObjectName on = new ObjectName(names[0]);
            list.add(new DependsFieldInjector(fields[i], on));
         }
      }
   }
}
