package javakurs.uebung06;


/**
 * {@link SimpleTableModelFridge} extends {@link FridgeEx2} with a table model
 * that is updated when the inventory of the fridge changes.
 *
 * @author Joerg Steffen, DFKI
 * @version $Id$
 */
public class SimpleTableModelFridge extends FridgeEx2 {

  /**
   * This contains the table model.
   */
  private SimplePropertiesTableModel tableModel;


  /**
   * This creates a new instance of {@link SimpleTableModelFridge}.
   */
  public SimpleTableModelFridge() {

    super();

    // init table model
    this.tableModel = new SimplePropertiesTableModel(this.getInventory());

    // init GUI
    new FridgeContentTable(this.tableModel);
  }


  /**
   * This adds or removes the given amount of the given product to the fridge.
   * It also updates the table model.
   *
   * @param amount
   *          the amount; may be positive or negative
   * @param product
   *          the name of the product
   */
  @Override
  public void modifyStock(double amount, String product) {

    // get current amount of the product
    double currentAmount = 0.0;
    String currentAmountString = this.getInventory().getProperty(product);
    if (currentAmountString == null) {
      this.message(product + " war noch nicht im K\u00fchlschrank.");
    }
    else {
      currentAmount = this.parseNumber(currentAmountString);
    }

    // check whether amount to remove is larger than available amount
    if (currentAmount + amount < 0) {
      this.message("Soviel ist nicht im K\u00fchlschrank!");
    }
    else {

      // inform about adding/removing
      if (amount > 0) {
        this.message("F\u00fcge " + this.formatNumber(amount) + " " + product
          + " hinzu.");
      }
      else {
        this.message("Entnehme " + this.formatNumber(-amount) + " " + product
          + ".");
      }

      // update amount
      currentAmount = currentAmount + amount;
      this.getInventory().setProperty(
        product, this.formatNumber(currentAmount));

      // update table model
      this.tableModel.updateValue(product, this.formatNumber(currentAmount));

      this.message(
        "Jetzt sind " + this.formatNumber(currentAmount) + " "
        + product + " vorhanden.");
    }
  }
}
