package org.jboss.cache.factories;

import org.jboss.cache.DataContainer;
import org.jboss.cache.RegionManager;
import org.jboss.cache.buddyreplication.BuddyFqnTransformer;
import org.jboss.cache.config.ConfigurationException;
import org.jboss.cache.factories.annotations.DefaultFactoryFor;
import org.jboss.cache.invocation.CacheInvocationDelegate;
import org.jboss.cache.invocation.InvocationContextContainer;
import org.jboss.cache.loader.CacheLoaderManager;
import org.jboss.cache.lock.LockStrategyFactory;
import org.jboss.cache.marshall.Marshaller;
import org.jboss.cache.marshall.VersionAwareMarshaller;
import org.jboss.cache.notifications.Notifier;
import org.jboss.cache.remoting.jgroups.ChannelMessageListener;
import org.jboss.cache.statetransfer.StateTransferManager;
import org.jboss.cache.transaction.TransactionTable;

/**
 * Simple factory that just uses reflection and an empty constructor of the component type.
 *
 * @author Manik Surtani (<a href="mailto:manik@jboss.org">manik@jboss.org</a>)
 * @since 2.1.0
 */
@DefaultFactoryFor(classes = {StateTransferManager.class, RegionManager.class, Notifier.class,
      ChannelMessageListener.class, CacheLoaderManager.class, Marshaller.class, InvocationContextContainer.class,
      CacheInvocationDelegate.class, TransactionTable.class, DataContainer.class, CommandsFactory.class,
      LockStrategyFactory.class, BuddyFqnTransformer.class})
public class EmptyConstructorFactory extends ComponentFactory
{
   @Override
   @SuppressWarnings("unchecked")
   protected <T> T construct(Class<T> componentType)
   {
      try
      {
         if (componentType.isInterface())
         {
            Class componentImpl;
            if (componentType.equals(Marshaller.class))
            {
               componentImpl = VersionAwareMarshaller.class;
            }
            else
            {
               // add an "Impl" to the end of the class name and try again
               componentImpl = getClass().getClassLoader().loadClass(componentType.getName() + "Impl");
            }

            return (T) componentImpl.newInstance();
         }
         else
         {
            return componentType.newInstance();
         }
      }
      catch (Exception e)
      {
         throw new ConfigurationException("Unable to create component " + componentType, e);
      }
   }
}
