/*
* 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.resource.deployment;

import java.beans.PropertyEditor;
import java.beans.PropertyEditorManager;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Collection;
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$
 */
public class AdminObjectFactory
{
   /** The logger */
   private static final Logger log = Logger.getLogger(AdminObjectFactory.class);

   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 values from the ra.xml 
      Collection raProperties = aomd.getProperties();
      if (raProperties != null && raProperties.size() != 0)
      {
         for (Iterator i = raProperties.iterator(); i.hasNext();)
         {
            ConfigPropertyMetaData cpmd = (ConfigPropertyMetaData) i.next();
            String name = cpmd.getName();
            String value = cpmd.getValue();
            if (value != null && value.length() > 0)
            {
               if (properties.containsKey(name))
               {
                  if (trace)
                     log.trace("AdminObject '" + jndiName + "' property=" + name + " IGNORING value=" + value +" specified in MBean properties."); 
               }
               else
               {
                  // 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);
                  }
               }
            }
         }
      }
      
      // 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;
   }
}
