/*
 * JBoss, the OpenSource J2EE webOS
 *
 * Distributable under LGPL license.
 * See terms of license at gnu.org.
 */
package org.jboss.hibernate.session;

import net.sf.hibernate.Session;
import org.jboss.logging.Logger;

import javax.transaction.Synchronization;

/**
 * Implementation of a transaction Synchronization for managing closure
 * of a hibernate Session on completion of the JTA transaction.
 *
 * @author <a href="mailto:steve@hibernate.org">Steve Ebersole</a>
 * @version $Revision: 1.1.2.4 $
 */
class TransactionSynch implements Synchronization
{
   private static Logger log = Logger.getLogger(TransactionSynch.class);

   private String name;
   private Session session;

   public TransactionSynch(String name, Session session)
   {
      if ( log.isTraceEnabled() )
      {
         log.trace("Preparing synch [name=" + name + ", session=" + session + "]");
      }

      if (session == null)
      {
         throw new IllegalArgumentException("Session to synchronize cannot be null");
      }

      this.name = name;
      this.session = session;
   }

   public void beforeCompletion()
   {
      if ( !session.isOpen() )
      {
         log.warn("Session already closed");
      }
      else
      {
         try
         {
            log.trace("Flushing Session");
            session.flush();
         }
         catch(Throwable t)
         {
            log.warn("Error flushing session");
         }
      }
   }

   public void afterCompletion(int status)
   {
      if ( session.isOpen() )
      {
         try
         {
            log.trace("Closing Session");
            session.close();
         }
         catch(Throwable t)
         {
            log.warn("Unable to close session");
         }
      }

      if ( session != HibernateContext.unbind(name) )
      {
         log.warn("Synch encountered different session in context while performing unbind");
      }
   }

}
