package org.jboss.cache.transaction;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import java.util.Properties;

/**
 * Simple transaction manager implementation that maintains transaction state
 * in memory only.
 *
 * @author bela
 * @version $Revision: 4834 $
 *          Date: May 15, 2003
 *          Time: 4:11:37 PM
 */
public class DummyTransactionManager extends DummyBaseTransactionManager
{
   static DummyTransactionManager instance = null;
   static DummyUserTransaction utx = null;

   static Log log = LogFactory.getLog(DummyTransactionManager.class);

   private static final long serialVersionUID = 4396695354693176535L;

   public static DummyTransactionManager getInstance()
   {
      if (instance == null)
      {
         instance = new DummyTransactionManager();
         utx = new DummyUserTransaction(instance);
         try
         {
            Properties p = new Properties();
            p.put(Context.INITIAL_CONTEXT_FACTORY, "org.jboss.cache.transaction.DummyContextFactory");
            Context ctx = new InitialContext(p);
            ctx.bind("java:/TransactionManager", instance);
            ctx.bind("UserTransaction", utx);
         }
         catch (NamingException e)
         {
            log.error("binding of DummyTransactionManager failed", e);
         }
      }
      return instance;
   }

   public static DummyUserTransaction getUserTransaction()
   {
      getInstance();
      return utx;
   }

   public static void destroy()
   {
      if (instance == null)
         return;
      try
      {
         Properties p = new Properties();
         p.put(Context.INITIAL_CONTEXT_FACTORY, "org.jboss.cache.transaction.DummyContextFactory");
         Context ctx = new InitialContext(p);
         ctx.unbind("java:/TransactionManager");
         ctx.unbind("UserTransaction");
      }
      catch (NamingException e)
      {
         log.error("unbinding of DummyTransactionManager failed", e);
      }
      instance.setTransaction(null);
      instance = null;
   }

}
