/*
 * MathDrill.java      Authors: Koffman and Wolz
 * Class that generates multiple math problems
 * and monitors the user's performance.
 * Uses class MathProblem and KeyIn.
 */
import psJava.KeyIn;
import javax.swing.JOptionPane;

public class MathDrill {
   private int correct;       // count of correct answers
   private int incorrect;     // count of incorrect answers

   // methods

   public char readChar(String prompt) {
     String charStr = JOptionPane.showInputDialog(prompt);
     return charStr.charAt(0);
   }

   // postcondition: Poses a number of arithmetic problems and evaluates
   //    the user's solution. The number of correct answers is stored in
   //    correct and the number of incorrect answers is stored in incorrect.
   public void doMultipleProblems() {
      // Generate, solve, and grade multiple math problems
      boolean moreProblems = true;
      while (moreProblems) {
        // Get new problem operator and difficulty.
        char op = readChar("Enter operator (+, -, *, /, %)");
        int diff =
            KeyIn.readInt("Enter difficulty level - 1, 2, 3 (highest)");

        // Generate new problem based on user's specification.
        MathProblem mP = new MathProblem(op, diff);

        // If the operator is valid, get and check the student's answer.
        if (mP.validOp())
           getAndCheckAnswer(mP);
        else
           System.out.println("Bad operator - try again");

        // See if user wants another problem.
        moreProblems = KeyIn.readBoolean("Try another problem?");
      } // end while
   }

   // precondition - mP is a valid math problem
   // postcondition - increments correct or incorrect based on user's answer.
   //    Also tells user she is correct or gives the correct answer
   private void getAndCheckAnswer(MathProblem mP) {
      int correctAnswer = mP.solveProblem();
      int userAnswer = KeyIn.readInt(mP.askProblem());
      String feedback;
      if (userAnswer == correctAnswer) {
        feedback = "correct, " + mP.toString() + " IS " +
                   userAnswer + " - good work";

        correct++;
      }
      else {
        feedback = "incorrect, " + mP.toString() +
                  " is " + correctAnswer;
        incorrect++;
      }
      JOptionPane.showMessageDialog(null, feedback);
      System.out.println(feedback);
   }

   public int getCorrect() { return correct; }
 
   public int getIncorrect() { return incorrect; }
}

