/*
  * JBoss, Home of Professional Open Source
  * Copyright 2005, JBoss Inc., and individual contributors as indicated
  * by the @authors tag. See the copyright.txt in the distribution for a
  * full listing of individual contributors.
  *
  * This is free software; you can redistribute it and/or modify it
  * under the terms of the GNU Lesser General Public License as
  * published by the Free Software Foundation; either version 2.1 of
  * the License, or (at your option) any later version.
  *
  * This software is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
  * License along with this software; if not, write to the Free
  * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
  * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
  */
package org.jboss.ejb3.injection;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import javax.management.ObjectName;
import org.jboss.annotation.ejb.Depends;
import org.jboss.aop.Advisor;
import org.jboss.ejb3.Container;
import org.jboss.ejb3.EJBContainer;
import org.jboss.logging.Logger;

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

   public static void loadDependencies(EJBContainer container, Class clazz)
   {
      HashSet<String> visitedMethods = new HashSet<String>();
      loadClassDepends(container, clazz);
      loadMethodDepends(visitedMethods, clazz, container);
      loadFieldDepends(clazz, container);
   }

   public static void loadClassDepends(EJBContainer container, Class clazz)
   {
      Depends dep = (Depends)((Advisor)container).resolveAnnotation(Depends.class);
      if (dep == null) return;
      for (String dependency : dep.value())
      {
         container.getDependencyPolicy().addDependency(dependency);
      }
   }

   private static void loadMethodDepends(HashSet<String> visitedMethods, Class clazz, EJBContainer container)
   {
      if (clazz == null || clazz.equals(Object.class))
      {
         return;
      }
      Method[] methods = clazz.getMethods();
      for (int i = 0; i < methods.length; i++)
      {
         Depends dep = (Depends) ((Advisor) container).resolveAnnotation(methods[i], Depends.class);
         if (dep != null)
         {
            if (!Modifier.isPrivate(methods[i].getModifiers()))
            {
               if (visitedMethods.contains(methods[i].getName())) continue;
               else visitedMethods.add(methods[i].getName());
            }
            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]);
            container.getDependencyPolicy().addDependency(names[0]);
         }
      }
      
      loadMethodDepends(visitedMethods, clazz.getSuperclass(), container);
   }

   private static void loadFieldDepends(Class clazz, EJBContainer container)
   {
      if (clazz == null || clazz.equals(java.lang.Object.class)) return;
      loadFieldDepends(clazz.getSuperclass(), container);
      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]);
            container.getDependencyPolicy().addDependency(names[0]);
         }
      }
   }

   public static List loadInjectors(Container container) throws Exception
   {
      Class clazz = container.getBeanClass();
      HashSet<String> visitedMethods = new HashSet<String>();
      ArrayList list = new ArrayList();
      loadMethodInjectors(visitedMethods, clazz, container, list);
      loadFieldInjectors(clazz, container, list);
      return list;
   }
   
   private static void loadMethodInjectors(HashSet<String> visitedMethods, Class clazz, Container container, ArrayList list) throws Exception
   {
      if (clazz == null || clazz.equals(Object.class))
      {
         return;
      }
      Method[] methods = clazz.getMethods();
      for (int i = 0; i < methods.length; i++)
      {
         Depends dep = (Depends) ((Advisor) container).resolveAnnotation(methods[i], Depends.class);
         if (dep != null)
         {
            if (!Modifier.isPrivate(methods[i].getModifiers()))
            {
               if (visitedMethods.contains(methods[i].getName())) continue;
               else visitedMethods.add(methods[i].getName());
            }

            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));
         }
      }
      if (clazz != null && !clazz.equals(Object.class))
      {
         loadMethodInjectors(visitedMethods, clazz.getSuperclass(), container, 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));
         }
      }
   }
}
