import acm.program.*;
import java.awt.*;
import java.util.*;
import java.io.*;

public class StanfordWho extends ConsoleProgram {
	
	private HashMap<String, ArrayList<String>> database = 
			new HashMap<String, ArrayList<String>>();
	
	public void run() {
		setFont("Courier-24");
		// 1. load data from file
		loadData();
		while(true) {
			// 2. print responses to query
			String query = readLine("? ");
			printQueryResponses(query);
		}
	}

	/**
	 * Load Data
	 * ----------------
	 * Loads all the students in sls.txt.
	 * Calls addLineToData on each line in the file
	 */
	private void loadData() {
		try {
			Scanner input = new Scanner(new File("sls.txt"));
			while(input.hasNextLine()) {
				String line = input.nextLine();
				// calls this method on each line
				addLineToData(line);
			}
			input.close();
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * Add Line to Data
	 * ----------------
	 * the input to this method is a studentLine
	 * a few examples:
	 *   "Chris Piech (cpiech)"
	 *   "Brahm Capoor (bcapoor)"
	 */
	private void addLineToData(String student) {
		int startParen = student.indexOf('(');
		int endParen = student.indexOf(')');
		
		// extract the sunetId
		String sunetId = student.substring(startParen + 1, endParen);
		// extract the name
		String name = student.substring(0, startParen);
		
		// extract the parts
		addPartToDatabase(sunetId, student);
		String[] parts = name.split(" ");
		for(String part : parts) {
			addPartToDatabase(part, student);
		}
	}

	// part "chris"
	// line "Chris Piech (cpiech)"
	private void addPartToDatabase(String part, String line) {
		// put 
		if(database.containsKey(part)) {
			ArrayList<String> lines = database.get(part);
			lines.add(line);
		} else {
			ArrayList<String> lines = new ArrayList<String>();
			lines.add(line);
			database.put(part, lines);
		}
		
	}

	/** 
	 * Print Query Responses
	 * ---------------------
	 * Print all students who have the query as either
	 * their sunetId or is one of their names
	 * Example queries:
	 * "Chris", "Capoor", "Maya", "mziv", "cHrIs"
	 */
	private void printQueryResponses(String query) {
		ArrayList<String> responses = database.get(query);
		for(String str : responses) {
			println(str);
		}
	}

}
