import java.util.Scanner;
import java.util.SortedMap;
import java.util.TreeMap;

public class TMCourse {
	// title of the course
	private String title;
	
	// the questions for that course
	private SortedMap<Integer,TMQuestion> questions = new TreeMap<Integer,TMQuestion>();
	
	// the constructor is off limits to the client since we want the client to use the 
	// factory method
	private TMCourse() {}
	
	/**
	 * Reads a course given the scanner on the input file
	 */
	public static TMCourse readCourse(Scanner scan) {
		TMCourse course = new TMCourse();
		// title
		course.title = scan.nextLine();
		// questions
		while (scan.hasNextInt()) {
			TMQuestion q = TMQuestion.readQuestion(scan);
			course.questions.put(q.getNumber(), q);
		}
		return course;
	}
	
	public void run() {
		Scanner scan = new Scanner(System.in);
		// start with the first question
		TMQuestion current = questions.get(questions.firstKey());
		
		while (true) {
			System.out.print(current.getText());
			System.out.print("> ");
			String answer = scan.nextLine();
			
			Integer next = current.getNextQuestionNumber(answer);
			if (next == null) {
				System.out.println("I don't understand");
			} else if (next == 0) {
				break;
			} else {
				current = questions.get(next);
			}
		}
		
		scan.close();
	}
	
	@Override
	public String toString() {
		String s = title + "\n"; // or System.lineSeparator(); to be OS independent
		for(Integer n : questions.keySet()) {
			s += questions.get(n) + "\n";
		}
		return s;
	}
}









