/*
 * 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.InvocationTargetException;
import java.lang.reflect.Method;
import javax.management.MBeanServer;
import javax.management.MBeanServerFactory;
import javax.management.ObjectName;
import org.jboss.ejb3.BeanContext;
import org.jboss.mx.util.MBeanProxyExt;

/**
 * @author <a href="mailto:kabir.khan@jboss.org">Kabir Khan</a>
 * @version $Revision: 1.1.4.4 $
 */
public class DependsMethodInjector implements Injector
{
   Method method;
   ObjectName on;

   public DependsMethodInjector(Method method, ObjectName on)
   {
      this.method = method;
      this.on = on;
   }

   public void inject(BeanContext ctx)
   {
      Class clazz = method.getParameterTypes()[0];
      Object value = null;

      if (clazz == ObjectName.class)
      {
         value = on;
      }
      else
      {
         MBeanServer server = (MBeanServer) MBeanServerFactory.findMBeanServer(null).get(0);
         value = MBeanProxyExt.create(clazz, on, server);
      }

      try
      {
         method.invoke(ctx.getInstance(), value);
      }
      catch (InvocationTargetException e)
      {
         throw new RuntimeException(e);
      }
      catch (IllegalAccessException e)
      {
         throw new RuntimeException(e);
      }
   }
}
