package model;

/**
 * @class SimpleCalculatorModel
 *
 */
public class SimpleCalculatorModel implements CalculatorModel {

  private final static int OP_ADD = 0;
  private final static int OP_SUB = 1;
  private final static int OP_DIV = 2;
  private final static int OP_MUL = 3;
  private final static int OP_NUL = -1;

  private double operand[] = new double[2]; 
  private int index = 0;
  private int op = OP_NUL;
  private boolean operandReady = false;

  /**
   */ 
  public void setOperand(double value) {
    operand[index] = value;
    operandReady = true;
  }

  public double getResult() {
    return operand[0];
  }

  public void operatorAddition() {

    calculate();   
    op = OP_ADD;

  }

  public void operatorSubtraction() {

    calculate();
    op = OP_SUB;

  }

  public void operatorDivision() {

    calculate();
    op = OP_DIV;

  }

  public void operatorMultiplication() {

    calculate();
    op = OP_MUL;    

  }

  public void operatorEquals() {

    if(op == OP_NUL)
      index = 0;
    else
      calculate();      
   
  }

  /**
   */
  private void calculate() {

    if(index > 0 && operandReady) {

      operandReady = !operandReady;

      switch(op) {
        case OP_ADD:
          operand[0] += operand[1];
          break;
        case OP_SUB:
          operand[0] -= operand[1];
          break;
        case OP_DIV:
          if(operand[1] == 0)
            operand[1] = 0;
          else
            operand[0] /= operand[1];
          break;
        case OP_MUL:
          operand[0] *= operand[1];
          break;
   
      }

      op = OP_NUL;

    } else 
      index = 1;
      
  }

}
