package org.jboss.cache.interceptors;

import org.jboss.cache.InvocationContext;
import org.jboss.cache.config.Option;
import org.jboss.cache.factories.annotations.Inject;
import org.jboss.cache.interceptors.base.CommandInterceptor;
import org.jboss.cache.transaction.GlobalTransaction;
import org.jboss.cache.transaction.TransactionEntry;
import org.jboss.cache.transaction.TransactionTable;

import javax.transaction.Status;
import javax.transaction.SystemException;
import javax.transaction.Transaction;
import javax.transaction.TransactionManager;

/**
 * Class providing some base functionality around manipulating transactions and global transactions withing invocation contexts.
 *
 * @author <a href="mailto:manik@jboss.org">Manik Surtani</a>
 */
public abstract class BaseTransactionalContextInterceptor extends CommandInterceptor
{
   protected TransactionTable txTable;
   protected TransactionManager txManager;

   @Inject
   private void injectDependencies(TransactionTable txTable, TransactionManager txManager)
   {
      this.txManager = txManager;
      this.txTable = txTable;
   }

   protected void copyInvocationScopeOptionsToTxScope(InvocationContext ctx)
   {
      // notify the transaction entry that this override is in place.
      TransactionEntry entry = txTable.get(ctx.getGlobalTransaction());
      if (entry != null)
      {
         Option txScopeOption = new Option();
         txScopeOption.setCacheModeLocal(ctx.getOptionOverrides() != null && ctx.getOptionOverrides().isCacheModeLocal());
         txScopeOption.setSkipCacheStatusCheck(ctx.getOptionOverrides() != null && ctx.getOptionOverrides().isSkipCacheStatusCheck());
         entry.setOption(txScopeOption);
      }
   }

   protected void setTransactionalContext(Transaction tx, GlobalTransaction gtx, TransactionEntry entry, InvocationContext ctx)
   {
      if (trace)
      {
         log.trace("Setting up transactional context.");
         log.trace("Setting tx as " + tx + " and gtx as " + gtx);
      }
      ctx.setTransaction(tx);
      ctx.setGlobalTransaction(gtx);
      if (entry == null)
      {
         if (gtx != null)
         {
            ctx.setTransactionEntry(txTable.get(gtx));
         }
         else if (tx == null)
         {
            // then nullify the transaction entry as well
            ctx.setTransactionEntry(null);
         }
      }
      else
      {
         ctx.setTransactionEntry(entry);
      }
   }

   /**
    * Returns true if transaction is rolling back, false otherwise
    */
   protected boolean isRollingBack(Transaction tx)
   {
      if (tx == null) return false;
      int status;
      try
      {
         status = tx.getStatus();
         return status == Status.STATUS_ROLLING_BACK || status == Status.STATUS_ROLLEDBACK;
      }
      catch (SystemException e)
      {
         log.error("failed getting transaction status", e);
         return false;
      }
   }
}
