package javakurs.musterloesung.uebung06;

import java.util.Stack;


/**
 * {@link AdvancedTableModelFridge} extends {@link FridgeEx2} with a table model
 * observing the inventory of the fridge.
 *
 * @author Joerg Steffen, DFKI
 * @version $Id: AdvancedTableModelFridge.java,v 1.1 2010/12/06 18:18:45 steffen Exp $
 */
public class AdvancedTableModelFridge extends FridgeEx2 {

  /**
   * This contains the command history;
   */
  private Stack<Command> commandStack;

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

    // we cannot use the super constructor since it loads the properties using
    // a simple properties object;
    // so we call all required methods here
    this.printWelcome();
    this.initProducts();

    // load properties using observable properties
    ObservableProperties obsProps = new ObservableProperties();
    this.loadInventory(obsProps);

    // init GUI and table model
    new FridgeContentTable(
      new AdvancedPropertiesTableModel(obsProps));

    // init history
    this.commandStack = new Stack<Command>();
  }


  /**
   * {@inheritDoc}
   */
  @Override
  public void modifyStock(Token amountTok, Token productTok, int sign) {

    // extract values from tokens
    double amount = 1.0;
    if (amountTok != null) {
      amount = this.parseNumber(amountTok.image);
    }

    // create a new command and add it to the history
    Command command =
      new FridgeCommand(this, productTok.image, amount * sign);
    this.commandStack.push(command);

    // execute the command
    command.execute();
  }


  /**
   * This revokes the previous command if {@code all} is {@code null} or all
   * commands if {@code all} is not {@code null}.
   *
   * @param all
   *          a token indicating if to undo all or only the previous
   *          command
   */
  public void undo(Token all) {

    if (this.commandStack.isEmpty()) {
      this.message("Es gibt nichts r\u00fcckg\u00e4ngig zu machen.");
    }
    else {
      if (null == all) {
        Command command = this.commandStack.pop();
        command.undo();
      }
      else {
        while (!this.commandStack.isEmpty()) {
          Command command = this.commandStack.pop();
          command.undo();
        }
      }
    }
  }
}
