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

import java.beans.PropertyEditor;
import java.beans.PropertyEditorManager;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;

import javax.management.ObjectName;

import org.jboss.deployment.DeploymentException;
import org.jboss.logging.Logger;
import org.jboss.resource.metadata.AdminObjectMetaData;
import org.jboss.resource.metadata.ConfigPropertyMetaData;

/**
 * An admin object factory
 *
 * @author  <a href="adrian@jboss.com">Adrian Brock</a>
 * @version $Revision: 1.1.2.2 $
 */
public class AdminObjectFactory
{
   // Constants -----------------------------------------------------
   
   /** The logger */
   private static final Logger log = Logger.getLogger(AdminObjectFactory.class);
   
   // Attributes ----------------------------------------------------
   
   // Static --------------------------------------------------------

   public static Object createAdminObject(String jndiName, ObjectName rarName, AdminObjectMetaData aomd, Properties properties) throws Exception
   {
      boolean trace = log.isTraceEnabled();
      
      // Get the current classloader
      ClassLoader cl = Thread.currentThread().getContextClassLoader();

      if (trace)
         log.trace("Creating AdminObject '" + jndiName + "' metadata=" + aomd + " rar=" + rarName + " properties=" + properties + " classloader=" + cl);
      
      // The interface class
      String interfaceName = aomd.getAdminObjectInterfaceClass();
      // Load the interface class class
      if (trace)
         log.trace("AdminObject '" + jndiName + "' loading interface=" + interfaceName); 
      Class interfaceClass = cl.loadClass(interfaceName);
      
      // Determine the implementation class
      String implName = aomd.getAdminObjectImplementationClass();
      if (implName == null)
         throw new DeploymentException("No implementation class for admin object '" + interfaceClass + "' ra=" + rarName);
      
      // Load the implementation class
      if (trace)
         log.trace("AdminObject '" + jndiName + "' loading implementation=" + implName); 
      Class implClass = cl.loadClass(implName);
      if (interfaceClass.isAssignableFrom(implClass) == false)
         throw new DeploymentException(implClass.getName() + " is not a '" + interfaceClass + "' ra=" + rarName);

      Object result = implClass.newInstance();
      if (trace)
         log.trace("AdminObject '" + jndiName + "' created instance=" + result); 
      
      // Apply the properties
      if (properties != null)
      {
         for (Iterator i = properties.entrySet().iterator(); i.hasNext();)
         {
            Map.Entry property = (Map.Entry) i.next();
            String name = (String) property.getKey();
            String value = (String) property.getValue();
            if (trace)
               log.trace("AdminObject '" + jndiName + "' property=" + name + " value=" + value); 
            
            // Pick up the property metadata
            ConfigPropertyMetaData cpmd = aomd.getProperty(name);
            if (cpmd == null)
               throw new DeploymentException("No property '" + name + "' for admin object '" + interfaceClass + "' ra=" + rarName);
            if (trace)
               log.trace("AdminObject '" + jndiName + "' property=" + name + " metadata=" + cpmd); 

            // Load the property class as defined in the meta data
            String typeName = cpmd.getType();
            if (trace)
               log.trace("AdminObject '" + jndiName + "' property=" + name + " loading class=" + typeName); 
            Class type = cl.loadClass(typeName); 
            
            // Find the property editor for this class
            PropertyEditor editor = PropertyEditorManager.findEditor(type);
            if (editor == null)
               throw new DeploymentException("No property editor found for property '" + name + " class='" + type + "' for admin object '" + interfaceClass + "' ra=" + rarName);
            editor.setAsText(value);
            Object object = editor.getValue();
            
            try
            {
               String setter = "set" + Character.toUpperCase(name.charAt(0));
               if (name.length() > 1)
                  setter = setter.concat(name.substring(1));
               Method method = implClass.getMethod(setter, new Class[] { type });
               if (trace)
                  log.trace("AdminObject '" + jndiName + "' property=" + name + " set=" + object); 
               method.invoke(result, new Object[] { object });
            }
            catch (InvocationTargetException e)
            {
               DeploymentException.rethrowAsDeploymentException("Error for property '" + name + "' class=" + implClass + "' for admin object '" + interfaceClass + "' ra=" + rarName, e.getTargetException());
            }
            catch (Throwable t)
            {
               DeploymentException.rethrowAsDeploymentException("Error for property '" + name + "' class=" + implClass + "' for admin object '" + interfaceClass + "' ra=" + rarName, t);
            }
         }
      }
      
      return result;
   }
   
   // Constructors --------------------------------------------------
   
   // Public --------------------------------------------------------
   
   // Package protected ---------------------------------------------

   // Protected -----------------------------------------------------
   
   // Private -------------------------------------------------------

   // Inner classes -------------------------------------------------

}