package com.sptci.echo2;

import java.io.Serializable;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

import nextapp.echo2.app.ListBox;
import nextapp.echo2.app.SelectField;
import nextapp.echo2.app.button.ToggleButton;
import nextapp.echo2.app.list.DefaultListModel;

import javax.jdo.JDOHelper;
import javax.jdo.PersistenceManager;

import com.sptci.ReflectionUtility;
import com.sptci.jdo.PersistenceManagerFactory;

/**
 * An <code>updater</code> used to update JavaBean objects from
 * their associated UI containers.  Adds JDO specific
 * actions such as making modifications within the
 * bounds of a <code>transaction</code>.
 *
 * <p>Copyright 2006 Sans Pareil Technologies, Inc.</p>
 * @author Rakesh Vidyadharan 2006-02-08
 * @version $Id: JDOModelUpdater.java,v 1.2 2006/02/13 23:13:49 rakesh Exp $
 */
public class JDOModelUpdater extends ModelUpdater implements Serializable
{
  /**
   * The logger used to log errors/warnings to.
   */
  private static transient final Logger logger =
    Logger.getLogger( "com.sptci.echo2.JDOModelUpdater" );

  /**
   * Create a new instance with the specified UI container and java 
   * bean.
   *
   * @param uiContainer The {@link #uiContainer} to use.
   * @param bean The {@link #bean} to use.
   */
  public JDOModelUpdater( Object uiContainer, Object bean )
  {
    super( uiContainer, bean );
  }

  /**
   * Over-ridden to conduct the updates with the bounds of a transaction
   * as mandated by JDO.  Starts a new transaction is necessary and
   * delegates processing to the super-class method implementation.
   *
   * @see ModelUpdater#update
   * @throws BindingException If errors are encountered while
   *   accessing or setting the fields.
   */
  public void update()
  {
    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.update();

      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." );
      }
    }
  }
}
