package javakurs.musterloesung.uebung06;

import java.util.Observable;
import java.util.Observer;

/**
 * {@link AdvancedPropertiesTableModel} extends
 * {@link SimplePropertiesTableModel} as an observer for
 * {@link ObservableProperties}.
 *
 * @author Ulrich Schaefer, DFKI
 * @author Joerg Steffen, DFKI
 * @version $Id: AdvancedPropertiesTableModel.java,v 1.1 2010/12/06 18:18:45 steffen Exp $
 */
public class AdvancedPropertiesTableModel
    extends SimplePropertiesTableModel
    implements Observer {

  /**
   * This contains the observable that is observed by this observer.
   */
  private PropertiesIF props;


  /**
   * This creates a new instance of {@link AdvancedPropertiesTableModel} for the
   * given observable properties.
   *
   * @param props
   *          observable properties to generate the model from
   */
  public AdvancedPropertiesTableModel(ObservableProperties props) {

    super(props);

    this.props = props;
    // register this table model as an observer of the properties
    props.addObserver(this);
  }


  /**
   * {@inheritDoc}
   */
  @Override
  public void update(Observable o, Object arg) {

    if (o == this.props && arg instanceof String) {
      int row = this.getRowForProperty((String)arg);
      if (-1 != row) {
        // update amount of existing product
        this.setValueAt(this.props.getProperty((String)arg), row, 1);
        // inform GUI about the change
        this.fireTableRowsUpdated(row, row);
      }
      else {
        // new product found
        row = this.addProperty((String)arg);
        this.setValueAt(arg, row, 0);
        this.setValueAt(this.props.getProperty((String)arg), row, 1);
        // inform GUI about the change
        fireTableRowsInserted(row, row);
      }
    }
  }
}
