package org.jboss.cache.factories;

import org.jboss.cache.config.ConfigurationException;
import org.jboss.cache.factories.annotations.DefaultFactoryFor;
import org.jboss.cache.transaction.TransactionManagerLookup;

import javax.transaction.TransactionManager;

/**
 * Uses a number of mechanisms to retrieve a transaction manager.
 *
 * @author Manik Surtani (<a href="mailto:manik@jboss.org">manik@jboss.org</a>)
 * @since 2.1.0
 */
@DefaultFactoryFor(classes = {TransactionManager.class})
public class TransactionManagerFactory extends ComponentFactory
{
   @Override
   @SuppressWarnings("unchecked")
   protected <T> T construct(Class<T> componentType)
   {
      // See if we had a TransactionManager injected into our config
      TransactionManager transactionManager = configuration.getRuntimeConfig().getTransactionManager();
      TransactionManagerLookup lookup = null;

      if (transactionManager == null)
      {
         // Nope. See if we can look it up from JNDI
         if (configuration.getTransactionManagerLookupClass() != null)
         {
            try
            {
               ClassLoader cl = Thread.currentThread().getContextClassLoader();
               if (cl == null) cl = getClass().getClassLoader();
               Class clazz = cl.loadClass(configuration.getTransactionManagerLookupClass());
               lookup = (TransactionManagerLookup) clazz.newInstance();
            }
            catch (Exception e)
            {
               throw new ConfigurationException("Problems looking up transaction manager", e);
            }
         }

         try
         {
            if (lookup != null)
            {
               transactionManager = lookup.getTransactionManager();
               configuration.getRuntimeConfig().setTransactionManager(transactionManager);
            }
         }
         catch (Exception e)
         {
            log.info("failed looking up TransactionManager, will not use transactions", e);
         }
      }
      return (T) transactionManager;
   }
}
