import java.util.*;
import java.io.*;

class UI {
    Database database = new Database();
    
    List<Entry> current = new ArrayList<Entry>();

    void command (Scanner sc) { 
	System.out.print(">"); System.out.flush();

	String command = sc.next();
	if(command.equals( "a" ))
	    add(sc);
	else if(command.equals( "c" ))
	    current(sc);
	else if(command.equals( "d" ))
	    delete(sc);
	else if(command.equals( "e" ))
	    exit(sc);
	else if(command.equals( "h" )) 
	    help(sc);
	else if(command.equals( "l" )) 
	    list(sc);
	else if(command.equals( "s" )) 
	    search(sc);
	else { 
	    sc.nextLine();
	    System.out.println("I did not understand that.");
	    System.out.println("Please type h for help.");
	}
    }

    void commandLoop(Scanner sc) {
	while (true) { 
	    command(sc);
	}
    }


    void add(Scanner sc) {
 
	String c = sc.next(); 
	Entry e = new Entry (c); 


	System.out.print("a "+c+">"); System.out.flush();
	String key = sc.next();
	while (!key.equals(".")) {
	    sc.skip("[ \t]*");
	    String attribute = sc.nextLine();
	    System.out.println("Key = "+key+ "; Attribute = <"+attribute+">");
	    e.add(key, attribute);

	    System.out.print("a "+c+">"); System.out.flush();
	    key = sc.next();
	} 
	sc.nextLine();
	current.clear();
	current.add(e);
	database.add(e);
    }

    void current (Scanner sc) {
	sc.nextLine();
	for (Entry e : current) { 
	    e.print(true);
	}
    }

    void delete (Scanner sc) {
	sc.nextLine();
	if (current.size() == 1) {
	    database.remove (current.get(0));
	    System.out.println("One entry deleted");
	    current.clear();
	}
	else if (current.size() == 0) {
	    System.out.println("No current entry to remove");
	}
	else {
	    System.out.println("Many current entries. Don't know which to remove");
	}
    }

    void exit (Scanner sc) {
	sc.nextLine();
	System.exit(0);
    }

    void help (Scanner sc) {
	sc.nextLine();
	try {
	    InputStream is = new FileInputStream("help.txt");
	    Reader r = new InputStreamReader(is);

	    BufferedReader br = new BufferedReader(r);

	    OutputStream os = System.out;
	    Writer w = new OutputStreamWriter(os);

	    String s = br.readLine();

	    while (s != null) {
		w.write(s);
		w.write("\n");
		s = br.readLine();
	    }
	    w.flush();
	    is.close();
        }
	catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    void list (Scanner sc) {
	sc.nextLine();
	database.print();
    }
    
    void search (Scanner sc) {
	String c = sc.next(); 
	String key = sc.next();
	sc.skip("[ \t]*");
	String attribute = sc.nextLine();
	System.out.println("Searching category = "+c+"; Key = "+key+ 
			   "; Attribute = <"+attribute+">");

	List<Entry> result;
	if (c.equals("*")) 
	    result = database.lookup(key, attribute);
	else 
	    result = database.lookup(c, key, attribute);

	System.out.println("Found "+result.size()+" entries");
	current.clear();
	current.addAll(result);
    } 
}
