package org.jboss.cache.search;

import org.hibernate.search.backend.TransactionContext;
import org.jboss.cache.notifications.event.NodeModifiedEvent;

import javax.transaction.Synchronization;
import javax.transaction.Transaction;

/**
 * This class implements the {@link org.hibernate.search.backend.TransactionContext} interface.  It
 * retrieves transaction context information from the {@link org.jboss.cache.notifications.event.NodeModifiedEvent} that gets passed in.
 * <p />
 * It is used by the {@link SearchableCoreListener} to pass transaction information to a Hibernate Search {@link org.hibernate.search.backend.Work} object.
 * <p />
 * @author Navin Surtani  - navin@surtani.org
 * @see SearchableCoreListener
 */
public class NodeModifiedTransactionContext implements TransactionContext
{

   NodeModifiedEvent event;

   /**
    * Creates a new instance of NodeModifiedTransactionContext.
    * <p />
    * @param event a NodeModifiedEvent to wrap.  Should not be null.
    * @throws NullPointerException if event is null.
    */
   public NodeModifiedTransactionContext(NodeModifiedEvent event)
   {
      if (event == null) throw new NullPointerException("event cannot be null");
      this.event = event;
   }

   /**
    * Returns a boolean value whether or not a transaction is in progress (JTA transaction and in this case *not*
    * an org.hibernate transaction).
    * @return true if a transaction is in progress, false otherwise.
    */
   public boolean isTransactionInProgress()
   {
      return (event.getTransaction() != null);
   }

   /**
    * Returns a JTA transaction.
    * @return a JTA transaction if one is available, or a null otherwise.
    * @see org.jboss.cache.notifications.event.NodeModifiedEvent#getTransaction()
    */

   public Object getTransactionIdentifier()
   {
      return event.getTransaction();
   }

   /**
    * Registers the synchronization passed in as a parameter with the ongoing transaction.
    * <p />
    * If there is no ongoing transaction, then this method will do nothing and simply return.
    * <p />
    * @param synchronization synchronization to register.  Must not be null.
    * @throws NullPointerException if the synchronization is null.
    */
   public void registerSynchronization(Synchronization synchronization)
   {
      if (synchronization == null) throw new NullPointerException("Synchronization passed in is null!");

      Transaction transaction = event.getTransaction();
      if (transaction != null)
      {
         try
         {
            transaction.registerSynchronization(synchronization);
         }
         catch (Exception e)
         {
            throw new RuntimeException(e);
         }
      }
   }
}
