package org.jboss.cache.factories;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jboss.cache.config.Configuration;
import org.jboss.cache.config.ConfigurationException;
import org.jboss.cache.factories.annotations.Inject;

/**
 * Factory that creates components used internally within JBoss Cache, and also wires dependencies into the components.
 * <p/>
 * The {@link org.jboss.cache.DefaultCacheFactory} is a special subclass of this, which bootstraps the construction of
 * other components.  When this class is loaded, it maintains a static list of known default factories for known
 * components, which it then delegates to, when actually performing the construction.
 * <p/>
 *
 * @author Manik Surtani (<a href="mailto:manik@jboss.org">manik@jboss.org</a>)
 * @see Inject
 * @see ComponentRegistry
 * @since 2.1.0
 */
public abstract class ComponentFactory
{
   protected final Log log = LogFactory.getLog(getClass());
   protected ComponentRegistry componentRegistry;
   protected Configuration configuration;

   /**
    * Constructs a new ComponentFactory.
    */
   public ComponentFactory(ComponentRegistry componentRegistry, Configuration configuration)
   {
      this.componentRegistry = componentRegistry;
      this.configuration = configuration;
   }
   
   /**
    * Constructs a new ComponentFactory.
    */
   public ComponentFactory()
   {
   }
   
   @Inject
   private void injectDependencies(Configuration configuration, ComponentRegistry componentRegistry)
   {
      this.configuration = configuration;
      this.componentRegistry = componentRegistry;
   }

   /**
    * Constructs a component.
    *
    * @param componentType type of component
    * @return a component
    */
   protected abstract <T> T construct(Class<T> componentType);

   protected void assertTypeConstructable(Class requestedType, Class... ableToConstruct)
   {
      boolean canConstruct = false;
      for (Class c : ableToConstruct)
      {
         canConstruct = canConstruct || requestedType.isAssignableFrom(c);
      }
      if (!canConstruct) throw new ConfigurationException("Don't know how to construct " + requestedType);
   }

}
