import java.io.Console;
import java.util.Arrays;

public class PasswordTestConsole {

	public static void main(String[] args) {
		boolean done = false;
		
		Console in = System.console();
		
		if(in == null) {
			System.out.println("No console. This doesn't work from Eclipse. Exiting.");
			System.exit(1);
		}
		
		Passwords passwd = new Passwords("password.txt");
		
		while(!done) {
			System.out.println();
			System.out.println("Menu:");
			System.out.println("(A)dd Username");
			System.out.println("(R)emove User");
			System.out.println("(C)heck Username");
			System.out.println("(L)ogon");
			System.out.println("(E)xit");
			
			String choice = in.readLine();
			if(choice == null) {
				done = true;
			}
			else if(choice.length() == 0) {
				continue;
			}
			else {
				char c = Character.toUpperCase(choice.charAt(0));
				switch(c) {
				case 'A':
					doAdd(passwd);
					break;
				case 'R':
					doRemove(passwd);
					break;
				case 'C':
					doCheck(passwd);
					break;
				case 'L':
					doLogin(passwd);
					break;
				case 'E':
					System.out.println("Good bye!");
					System.exit(0);
					break;
				}
			}
		}
	}
	
	public static void doAdd(Passwords passwd) {
		Console in = System.console();
		String name = in.readLine("Enter a username: ");
		char[] pass1 = in.readPassword("Enter your password: ");
		char[] pass2 = in.readPassword("Enter your password again: ");
		if(Arrays.equals(pass1, pass2)) {
			if(passwd.addUser(name, pass1)) {
				System.out.printf("User %s added successfully.\n", name);
			}
			else {
				System.out.printf("Failed to add %s.\n", name);
				
			}
			//erase the password
			Arrays.fill(pass1, ' ');
			Arrays.fill(pass2, ' ');
		}
		else {
			System.out.println("The passwords are different.");
		}
	}
	
	public static void doRemove(Passwords passwd) {
		Console in = System.console();
		String name = in.readLine("Enter a username: ");
		if(passwd.removeUser(name)) {
			System.out.printf("User %s removed successfully.\n", name);
		}
		else {
			System.out.printf("Failed to remove %s.\n", name);

		}
		
	}
	
	public static void doCheck(Passwords passwd) {
		Console in = System.console();

		String name = in.readLine("Enter a username: ");
		if(passwd.isUser(name)) {
			System.out.printf("Username exists for %s..\n", name);
		}
		else {
			System.out.printf("No such username: %s.\n", name);

		}
		
	}
	
	public static void doLogin(Passwords passwd) {
		Console in = System.console();
		String name = in.readLine("Enter a username: ");
		char[] pass1 = in.readPassword("Enter your password: ");
		if(passwd.authenticateUser(name, pass1)) {
			System.out.printf("User %s successfully authenticated.\n", name);
		}
		else {
			System.out.printf("Failed to authenticate %s.\n", name);

		}
		//erase the password
		Arrays.fill(pass1, ' ');

		
	}

}
