package org.jboss.cache.factories;

import org.jboss.cache.NodeFactory;
import org.jboss.cache.RPCManager;
import org.jboss.cache.config.ConfigurationException;
import org.jboss.cache.config.RuntimeConfig;
import org.jboss.cache.factories.annotations.DefaultFactoryFor;
import org.jboss.cache.util.BeanUtils;

import java.lang.reflect.Method;

/**
 * An extension of the EmptyConstructorFactory that places a component in the {@link RuntimeConfig} after creating it.
 *
 * @author Manik Surtani (<a href="mailto:manik@jboss.org">manik@jboss.org</a>)
 * @since 2.1.0
 */
@DefaultFactoryFor(classes = {RPCManager.class, NodeFactory.class})
public class RuntimeConfigAwareFactory extends EmptyConstructorFactory
{
   @Override
   @SuppressWarnings("unchecked")
   protected <T> T construct(Class<T> componentType)
   {
      T component = super.construct(componentType);

      Method setter = BeanUtils.setterMethod(RuntimeConfig.class, componentType);
      if (setter != null)
      {
         try
         {
            setter.invoke(configuration.getRuntimeConfig(), component);
         }
         catch (Exception e)
         {
            throw new ConfigurationException("Unable to put newly constructed component of type " + componentType + " in the RuntimeConfig", e);
         }
      }
      return component;
   }
}
