
// Parser.java
// Andrew Davison, Nov 2018, ad@fivedots.coe.psu.ac.th


/* This parser repeatedly reads a line from the terminal and
   tries to interpret the line as a two word command. It returns the command
   pair as a Command object.

   The parser checks the user input command against
   the known commands, and if the input isn't recognized, then the parser
   returns an 'unknown' Command object.
   
 * @author  Michael Kolling and David J. Barnes
 * @version 2006.03.30
*/


import java.util.*;


public class Parser 
{
  private CommandWords commands; // holds all the valid command words
  private Scanner reader;        // source of command input


  public Parser() 
  {
    commands = new CommandWords();
    reader = new Scanner(System.in);
  }


  public Command getCommand() 
  {
    System.out.print(">> "); // print prompt
    String inputLine = reader.nextLine();

    // Extyract up to two words from the input line
    Scanner tokenizer = new Scanner(inputLine);
    String word1 = null;
    String word2 = null;
    if (tokenizer.hasNext()) {
      word1 = tokenizer.next(); 
      if (tokenizer.hasNext())
        word2 = tokenizer.next();
      // ignore the rest of the input line
    }

    /* Check whether this word is known. If so, create a Command object.
       If not, then create a "null" Command (which represent an unknown command). */
    if (commands.isCommand(word1))
      return new Command(word1, word2);
    else
      return new Command(null, word2); 
  }  // end of getCommand()


}  // end of Parser class
