package viewController;

import java.awt.*;
import model.*;

public class NGPCalculator extends NGP.Containers.Frame { 
  
  private CalculatorModel model = new SimpleCalculatorModel();
  private NGP.Components.Label lcd;
  private String value = "";

  public NGPCalculator() {

    super("NGP Calculator");

    NGP.Containers.Panel base = new NGP.Containers.Panel(this);  
    
    lcd = new NGP.Components.Label(new NGP.Containers.Row(base), "");
    
    // Add the Buttons    
    NGP.Containers.GridContainer grid = new NGP.Containers.GridContainer(new NGP.Containers.Row(base), 4, 4);

    new NumberButton(grid, "1");
    new NumberButton(grid, "2");
    new NumberButton(grid, "3");
    
    new OperatorButton(grid, "+");
    
    new NumberButton(grid, "4");
    new NumberButton(grid, "5");
    new NumberButton(grid, "6");

    new OperatorButton(grid, "-");
    
    new NumberButton(grid, "7");
    new NumberButton(grid, "8");
    new NumberButton(grid, "9");

    new OperatorButton(grid, "/");

    new NumberButton(grid, "0");
    new NumberButton(grid, ".");

    new OperatorButton(grid, "=");
    new OperatorButton(grid, "*");

  }

  // Update the text
  private void numberPressed(String number) {   

    if(value.length() > 0 || !number.equals("0")) {

      String s = value + number;

      try {

        model.setOperand(Double.parseDouble(s));
        lcd.setText(s);
        value = s;

      } catch(NumberFormatException e) { /* NaN */ }

    }

  }

  // Do some math
  private void operatorPressed(String number) {  
    
    if(number.equals("+")) 
      model.operatorAddition();
    else if(number.equals("-")) 
      model.operatorSubtraction();
    else if(number.equals("/")) 
      model.operatorDivision();
    else if(number.equals("*"))
      model.operatorMultiplication();    
    else
      model.operatorEquals();    

    lcd.setText(String.valueOf(model.getResult()));
    value = "";

  }

  class NumberButton extends NGP.Components.PushButton {
  
    public NumberButton(NGP.Container container, String number) {
      super(container, number);
    }

    public void release() {
      numberPressed(getText());
    }
    
  }

  class OperatorButton extends NGP.Components.PushButton {
  
    public OperatorButton(NGP.Container container, String number) {
      super(container, number);
    }

    public void release() {
      operatorPressed(getText());
    }

  }

  public static void main(String[] args) {
    
    NGPCalculator calc = new NGPCalculator();

    calc.setDimension(new Dimension(200,250));
    calc.setDefaultCloseOperation(EXIT_ON_CLOSE);   
    calc.show();

  }
 
}
