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

/* Answer for Problem 4 (two pages) */
// don't worry about importing packages
/** MPedigree Redux **/
public class MPedigreeRedux extends ConsoleProgram implements SimpleServerListener {

    // the server instance
    private SimpleServer server = new SimpleServer(this, 8000);

    // the file with all of the secret codes
    private String CODE_FILE_NAME = "secretCodes.txt";

    // Map of code to whether it has already been checked
    private HashMap<String, Boolean> codesMap;

    public void run() {
        codesMap = new HashMap<String, Boolean>();
        try {
            Scanner scanner = new Scanner(new File(CODE_FILE_NAME));
            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                codesMap.put(line, false);
            }
            scanner.close();
        } catch (IOException ex) {
            println("The secret code file could not be loaded");
        }
        
        server.start();
    }

    public String requestMade(Request r) {
        String command = r.getCommand();
        if (command.equals("check")) {
            if (!r.hasParam("code")) {
                return "missing parameter";
            }

            String code = r.getParam("code");
            if (!codesMap.containsKey(code)) {
                return "invalid code";
            }

            if (codesMap.get(code)) {
                return "already checked";
            } else {
                codesMap.put(code, true);
                return "success";
            }
        } else {
            return "unknown command";
        }
    }
}