/*
 * JBoss, Home of Professional Open Source
 * Copyright 2007, Red Hat Middleware LLC, and individual contributors
 * 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.managed.plugins.factory;

import java.lang.reflect.UndeclaredThrowableException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.WeakHashMap;

import org.jboss.beans.info.spi.BeanInfo;
import org.jboss.beans.info.spi.PropertyInfo;
import org.jboss.config.plugins.property.PropertyConfiguration;
import org.jboss.config.spi.Configuration;
import org.jboss.managed.api.ManagedObject;
import org.jboss.managed.api.ManagedProperty;
import org.jboss.managed.api.MutableManagedObject;
import org.jboss.managed.api.annotation.ManagementObjectRef;
import org.jboss.managed.api.annotation.ManagementRuntimeRef;
import org.jboss.managed.api.factory.ManagedObjectFactory;
import org.jboss.managed.spi.factory.InstanceClassFactory;
import org.jboss.managed.spi.factory.RuntimeComponentNameTransformer;
import org.jboss.metadata.spi.MetaData;
import org.jboss.metatype.api.types.ArrayMetaType;
import org.jboss.metatype.api.types.CollectionMetaType;
import org.jboss.metatype.api.types.MetaType;
import org.jboss.metatype.api.values.ArrayValueSupport;
import org.jboss.metatype.api.values.CollectionValueSupport;
import org.jboss.metatype.api.values.GenericValue;
import org.jboss.metatype.api.values.GenericValueSupport;
import org.jboss.metatype.api.values.MetaValue;
import org.jboss.metatype.api.values.MetaValueFactory;
import org.jboss.reflect.spi.TypeInfo;
import org.jboss.util.NotImplementedException;

/**
 * A base InstanceClassFactory implementation that uses jboss reflection to
 * get/set values on the underlying property object.
 * 
 * Runtime component names are handled via a mapping from TypeInfo to
 * {@linkplain RuntimeComponentNameTransformer} using property ManagementRuntimeRef
 * information.
 * 
 * @param <T> the instance type
 * @author Scott.Stark@jboss.org
 * @version $Revision: 80522 $
 */
public abstract class AbstractInstanceClassFactory<T>
   implements InstanceClassFactory<T>
{
   /** The configuration */
   private Configuration configuration = new PropertyConfiguration();
   /** The meta value factory */
   private MetaValueFactory metaValueFactory = MetaValueFactory.getInstance();
   /** The instance to name transformers */
   private Map<TypeInfo, RuntimeComponentNameTransformer> transformers = new WeakHashMap<TypeInfo, RuntimeComponentNameTransformer>();
   /** The ManagedObjectFactory used in getValue for MANAGED_OBJECT_META_TYPEs */
   private ManagedObjectFactory mof;

   public AbstractInstanceClassFactory()
   {
      this(null);
   }
   /**
    * Create an AbstractInstanceClassFactory with a ManagedObjectFactory. The
    * ManagedObjectFactory is neede for GenericValue creation.
    * @param mof - the ManagedObjectFactory delegated to for GenericValue handling.
    * @see #getManagedObjectValue(BeanInfo, ManagedProperty, Object)
    * @see #getManagedObjectArray(BeanInfo, ManagedProperty, Object)
    */
   public AbstractInstanceClassFactory(ManagedObjectFactory mof)
   {
      this.mof = mof;
   }

   public Map<TypeInfo, RuntimeComponentNameTransformer> getTransformers()
   {
      return transformers;
   }
   public void setTransformers(Map<TypeInfo, RuntimeComponentNameTransformer> transformers)
   {
      this.transformers = transformers;
   }
   public void setNameTransformers(Class<?> clazz, RuntimeComponentNameTransformer transformer)
   {
      TypeInfo type = configuration.getTypeInfo(clazz);
      setNameTransformers(type, transformer);
   }

   public void setNameTransformers(TypeInfo type, RuntimeComponentNameTransformer transformer)
   {
      synchronized (transformers)
      {
         if (transformer == null)
            transformers.remove(type);
         else
            transformers.put(type, transformer);
      }
   }

   public Configuration getConfiguration()
   {
      return configuration;
   }
   public void setConfiguration(Configuration configuration)
   {
      this.configuration = configuration;
   }

   public MetaValueFactory getMetaValueFactory()
   {
      return metaValueFactory;
   }
   public void setMetaValueFactory(MetaValueFactory metaValueFactory)
   {
      this.metaValueFactory = metaValueFactory;
   }

   public ManagedObjectFactory getMof()
   {
      return mof;
   }
   public void setMof(ManagedObjectFactory mof)
   {
      this.mof = mof;
   }

   /**
    * Default InstanceClassFactory implementation simply returns the
    * attachment class. 
    */
   public Class<?> getManagedObjectClass(T attachment)
         throws ClassNotFoundException
   {
      return attachment.getClass();
   }

   public Object getComponentName(BeanInfo beanInfo, ManagedProperty property,
         T attachment, MetaValue value)
   {
      if (beanInfo != null && property != null && value != null)
      {
         String name = getPropertyName(property);
         PropertyInfo propertyInfo = beanInfo.getProperty(name);

         ManagementRuntimeRef componentRef = propertyInfo.getUnderlyingAnnotation(ManagementRuntimeRef.class);
         if (componentRef != null)
         {
            Object original = this.unwrapValue(beanInfo, property, value);
            try
            {
               Class<? extends RuntimeComponentNameTransformer> tClass = componentRef.transformer();
               RuntimeComponentNameTransformer transformer;
               if (tClass != ManagementRuntimeRef.DEFAULT_NAME_TRANSFORMER.class)
                  transformer = getComponentNameTransformer(configuration.getTypeInfo(tClass));
               else
                  transformer = getComponentNameTransformer(propertyInfo.getType());

               return (transformer != null) ? transformer.transform(original) : original;
            }
            catch (Throwable t)
            {
               throw new UndeclaredThrowableException(t);
            }
         }
      }
      return null;
   }

   public MetaValue getValue(BeanInfo beanInfo, ManagedProperty property,
         MetaData metaData, T object)
   {
      String name = getPropertyName(property);
      PropertyInfo propertyInfo = beanInfo.getProperty(name);

      Object value;
      try
      {
         value = propertyInfo.get(object);
      }
      catch (RuntimeException e)
      {
         throw e;
      }
      catch (Error e)
      {
         throw e;
      }
      catch (Throwable t)
      {
         throw new RuntimeException("Error getting property " + name + " for " + object.getClass().getName(), t);
      }

      if (value == null)
         return null;

      MetaType propertyType = property.getMetaType();
      if (AbstractManagedObjectFactory.MANAGED_OBJECT_META_TYPE == propertyType)
      {
         GenericValue gvs = getManagedObjectValue(beanInfo, property, metaData, value);
         return gvs;
      }
      else if (propertyType.isArray())
      {
         ArrayMetaType arrayType = ArrayMetaType.class.cast(propertyType);
         if (AbstractManagedObjectFactory.MANAGED_OBJECT_META_TYPE == arrayType.getElementType())
         {
            ArrayMetaType moType = new ArrayMetaType(1, AbstractManagedObjectFactory.MANAGED_OBJECT_META_TYPE);
            ArrayValueSupport moArrayValue = new ArrayValueSupport(moType);
            List<GenericValue> tmp = getManagedObjectArray(beanInfo, property, metaData, value);
            GenericValue[] mos = new GenericValue[tmp.size()];
            moArrayValue.setValue(tmp.toArray(mos));
            return moArrayValue;
         }
      }
      else if (propertyType.isCollection())
      {
         CollectionMetaType collectionType = CollectionMetaType.class.cast(propertyType);
         if (AbstractManagedObjectFactory.MANAGED_OBJECT_META_TYPE == collectionType.getElementType())
         {
            List<GenericValue> tmp = getManagedObjectArray(beanInfo, property, metaData, value);
            GenericValue[] mos = new GenericValue[tmp.size()];
            CollectionMetaType moType = new CollectionMetaType(propertyType.getClassName(), AbstractManagedObjectFactory.MANAGED_OBJECT_META_TYPE);
            tmp.toArray(mos);
            return new CollectionValueSupport(moType, mos);
         }
      }

      return getNonManagedObjectValue(beanInfo, property, propertyInfo, value);
   }

   /**
    * Set a value
    *
    * @param beanInfo the bean info
    * @param property the property
    * @param object the object
    * @param value the meta value
    */
   public void setValue(BeanInfo beanInfo, ManagedProperty property, T object, MetaValue value)
   {
      String name = getPropertyName(property);
      PropertyInfo propertyInfo = beanInfo.getProperty(name);

      Object unwrapValue = unwrapValue(beanInfo, property, value);
      try
      {
         if(unwrapValue instanceof ManagedObject)
         {
            ManagedObject mo = (ManagedObject) unwrapValue;
            setManagedObject(beanInfo, propertyInfo, object, mo);
         }
         else
            setValue(beanInfo, propertyInfo, object, unwrapValue);
      }
      catch(Throwable t)
      {
         throw new UndeclaredThrowableException(t);
      }
   }

   public GenericValue getManagedObjectValue(ManagedProperty property,
         ManagedObject value)
      {
         return getManagedObjectValue(null, property, null, value);
      }
   public GenericValue getManagedObjectValue(ManagedProperty property, MetaData metaData,
      ManagedObject value)
   {
      return getManagedObjectValue(null, property, metaData, value);
   }

   protected GenericValue getManagedObjectValue(BeanInfo beanInfo, ManagedProperty property,
      MetaData metaData, Object value)
   {
      // Look for a ManagementObjectRef
      ManagementObjectRef ref = (ManagementObjectRef) property.getAnnotations().get(ManagementObjectRef.class.getName());
      String moName = (ref != null ? ref.name() : value.getClass().getName());
      String moNameType = (ref != null ? ref.type() : "");
      ManagedObject mo;
      if(value instanceof ManagedObject)
         mo = ManagedObject.class.cast(value);
      else
         mo = mof.initManagedObject(value, null, metaData, moName, moNameType);
      ManagedObject parentMO = property.getManagedObject();
      if(parentMO != null && mo instanceof MutableManagedObject)
      {
         MutableManagedObject mmo = (MutableManagedObject) mo;
         mmo.setParent(parentMO);
      }
      return new GenericValueSupport(AbstractManagedObjectFactory.MANAGED_OBJECT_META_TYPE, mo);
   }
   protected List<GenericValue> getManagedObjectArray(BeanInfo beanInfo, ManagedProperty property,
         MetaData metaData, Object value)
   {
      Collection<?> cvalue = getAsCollection(value);
      List<GenericValue> tmp = new ArrayList<GenericValue>();
      for(Object element : cvalue)
      {
         GenericValue gv = getManagedObjectValue(beanInfo, property, metaData, element);
         tmp.add(gv);
      }
      return tmp;
   }
   protected MetaValue getNonManagedObjectValue(BeanInfo beanInfo, ManagedProperty property,
         PropertyInfo propertyInfo, Object value)
   {
      return metaValueFactory.create(value, propertyInfo.getType());
   }
   /**
    * Currently just a stub method subclasses have to override to avoid
    * the NotImplementedException.
    * 
    * TODO: how to map the managed properties onto the corresponding attachment
    * object, create another ManagedObject?
    *
    * @param beanInfo
    * @param propertyInfo
    * @param object
    * @param mo
    */
   protected void setManagedObject(BeanInfo beanInfo, PropertyInfo propertyInfo,
         T object, ManagedObject mo)
   {
      throw new NotImplementedException("Use a custom InstanceClassFactory, property="+propertyInfo);
   }

   /**
    * Get component name transformer.
    *
    * @param type the type info
    * @return transformer instance
    * @throws Throwable for any error
    */
   protected RuntimeComponentNameTransformer getComponentNameTransformer(TypeInfo type) throws Throwable
   {
      synchronized(transformers)
      {
         RuntimeComponentNameTransformer transformer = transformers.get(type);
         if (transformer != null)
            return transformer;

         TypeInfo rcntType = configuration.getTypeInfo(RuntimeComponentNameTransformer.class);
         if (rcntType.isAssignableFrom(type))
         {
            BeanInfo beanInfo = configuration.getBeanInfo(type);
            RuntimeComponentNameTransformer newTransformer = (RuntimeComponentNameTransformer)beanInfo.newInstance();
            transformers.put(type, newTransformer);
            return newTransformer;
         }

         return null;
      }
   }

   protected Object unwrapValue(BeanInfo beanInfo, ManagedProperty property, MetaValue value)
   {
      String name = getPropertyName(property);
      PropertyInfo propertyInfo = beanInfo.getProperty(name);

      Object unwrapValue = metaValueFactory.unwrap(value, propertyInfo.getType());
      return unwrapValue;
   }
   protected void setValue(BeanInfo beanInfo, PropertyInfo propertyInfo, Object object, Object unwrapValue)
      throws Throwable
   {
      propertyInfo.set(object, unwrapValue);
   }

   protected Collection<?> getAsCollection(Object value)
   {
      if( value.getClass().isArray() )
         return Arrays.asList(value);
      else if (value instanceof Collection)
         return Collection.class.cast(value);
      return null;
   }

   /**
    * Get the property name.
    *
    * @param property managed property
    * @return property name
    */
   protected String getPropertyName(ManagedProperty property)
   {
      // First look to the mapped name
      String name = property.getMappedName();
      if (name == null)
         property.getName();
      return name;
   }
}
