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 com.sptci.ReflectionUtility;

/**
 * An <code>updater</code> used to update JavaBean objects from
 * their associated UI containers.
 *
 * <p>Copyright 2006 Sans Pareil Technologies, Inc.</p>
 * @author Rakesh Vidyadharan 2006-02-08
 * @version $Id: ModelUpdater.java,v 1.3 2006/02/15 00:48:26 rakesh Exp $
 */
public class ModelUpdater extends Updater implements Serializable
{
  /**
   * The logger used to log errors/warnings to.
   */
  private static transient final Logger logger =
    Logger.getLogger( "com.sptci.echo2.ModelUpdater" );

  /**
   * 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 ModelUpdater( Object uiContainer, Object bean )
  {
    super( uiContainer, bean );
  }

  /**
   * Update the fields of the {@link #bean} with the data in
   * similarly named fields in {@link #uiContainer}.
   *
   * @see ReflectionUtility#fetchField
   * @see ReflectionUtility#fetchMethod
   * @throws BindingException If errors are encountered while
   *   accessing or setting the fields.
   */
  public void update()
  {
    try
    {
      for ( Map.Entry<String, Object> entry : uiValues().entrySet() )
      {
        try
        {
          Object object = 
            ReflectionUtility.fetchObject( entry.getKey(), bean );

          Method method = 
            ReflectionUtility.fetchMutator( entry.getKey(), bean );
          method.invoke( bean, entry.getValue() );
        }
        catch ( NoSuchFieldException nsfe )
        {
          logger.finer( com.sptci.util.StringUtilities.stackTrace( nsfe ) );
        }
      }
    }
    catch ( Throwable t )
    {
      throw new BindingException( t );
    }
  }
}
