package com.sptci.echo2;

import java.beans.PropertyChangeEvent;
import java.beans.IntrospectionException;
import java.io.Serializable;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.jdo.JDOHelper;
import com.sptci.jdo.PersistenceManagerFactory;

/**
 * A sub-class of {@link PropertyChangeListener} used to synchronise 
 * changes made to properties in UI components to the {@link #bean} 
 * JDO object.
 *
 * <p>Copyright 2006 Sans Pareil Technologies, Inc.</p>
 * @author Rakesh Vidyadharan 2006-05-05
 * @version $Id: JDOModelPropertyChangeListener.java,v 1.3 2006/02/14 22:40:32 rakesh Exp $
 */
public class JDOModelPropertyChangeListener extends ModelPropertyChangeListener 
  implements Serializable
{
  /**
   * The logger used to log errors to
   */
  private static transient final Logger logger =
    Logger.getLogger( "com.sptci.echo2.JDOModelPropertyChangeListener" );

  /**
   * Create a new instance of the class using the specified java bean.
   *
   * @param bean The data object which is to be managed.
   * @throws IntrospectionException If errors are encountered while
   *   introspecting the {@link #bean} class.
   */
  public JDOModelPropertyChangeListener( Object bean )
    throws IntrospectionException
  {
    super( bean );
  }

  /**
   * Over-riddent implementation of the method defined in <code>
   * PropertyChangeListener</code>.  Start a new JDO <code>transaction
   * </code>, apply the changes using {@link 
   * ModelPropertyChangeListener#propertyChange}, and then 
   * <code>commit</code> the <code>transaction</code>.
   *
   * @param event A <code>PropertyChangeEvent</code> object describing 
   *   the event source and the property that has changed.
   * @throws BindingException If errors are encountered while
   *   attempting to modify the {@link #bean}.
   */
  public void propertyChange( PropertyChangeEvent event )
  {
    PersistenceManager persistenceManager = null;
    boolean active = false;

    try
    {
      persistenceManager = JDOHelper.getPersistenceManager( bean );
      if ( persistenceManager == null )
      {
        persistenceManager = 
          PersistenceManagerFactory.getPersistenceManager();
      }

      active = persistenceManager.currentTransaction().isActive();

      if ( ! active )
      {
        persistenceManager.currentTransaction().begin();
      }

      super.propertyChange( event );

      if ( ! active )
      {
        persistenceManager.currentTransaction().commit();
      }
    }
    catch ( Throwable t )
    {
      throw new BindingException( t );
    }
    finally
    {
      if ( persistenceManager != null && ! active &&
          persistenceManager.currentTransaction().isActive() )
      {
        persistenceManager.currentTransaction().rollback();
        logger.warning( "Unknown problem.  Rollling back transaction." );
      }
    }
  }
}
