package smprot; 

import java.io.BufferedReader;
import java.io.PrintWriter;

import smserve_main.Messagequeuehandler;
import smserve_main.Userhandler;

public final class Chooser {
	public static void choose(String pMsg, BufferedReader pBr, PrintWriter pPw) throws Exception {
		Chooser.choose(pMsg, pBr, pPw, "");
	}
	
	public static void  choose(String pMsg, BufferedReader pBr, PrintWriter pPw, String pUser)throws Exception{
		String [] msg = pMsg.replace("\n", " ").split(" ");
		if (msg[0].equals("HELO")) {
				Chooser.choose(pBr.readLine(), pBr, pPw, msg[1]);
		} else if(msg[0].equals("PW")) {
				if(Auther.auth(pUser, msg[1])) {
					pPw.println("OK");
					pPw.flush();
					Chooser.choose(pBr.readLine(), pBr, pPw, pUser);
				} else { pPw.println("DENY"); pPw.flush(); }
		} else if(msg[0].equals("CHPW")) {
			if (Auther.chpw(pUser, msg[1])) {
				pPw.println("OK");
			} else { pPw.println("DENY"); }
			pPw.flush();
		} else if(msg[0].equals("HELP")) {
			pPw.printf("HELO user \t\t# user is saying hello\nPW password \t\t# after saying hello he shows his pass\nMSG MSGTO:user:message \t# sending message to user\nMSG GETNEW \t\t# Get new messages\nREG user password \t# registering user with password\nLISTUSERS \t\t# Shows all users on server\nLISTMSGS \t\t# Shows all messages for authed user\nQUIT \t\t\t# Ends conversation\nEXIT \t\t\t# Same as QUIT\n");			
			pPw.flush();
			Chooser.choose(pBr.readLine(), pBr, pPw, pUser);
		} else if(msg[0].equals("MSG")){
			if (msg[1].substring(0,5).equals("MSGTO")) {
				Messagehandler mh = new Messagehandler();
				mh.addPlainMessage(pUser, pMsg.substring(3, pMsg.length()));
				pPw.println("OK");
			} else if(msg[1].equals("GETNEW")) {
				Messagequeuehandler mqh = new Messagequeuehandler();
				pPw.println(mqh.getNewMessages(pUser));
			}
			pPw.flush();
			Chooser.choose(pBr.readLine(), pBr, pPw, pUser);
		} else if(msg[0].equals("REG")){
			Userhandler uh = new Userhandler();
			uh.addUser(pMsg);
			Chooser.choose(pBr.readLine(), pBr, pPw, pUser);
		} else if(msg[0].equals("LISTUSERS")) {
			Userhandler uh = new Userhandler();
			pPw.println(uh.listUsers());
			pPw.flush();
			Chooser.choose(pBr.readLine(), pBr, pPw, pUser);
		} else if(msg[0].equals("LISTMSGS")) {
			Messagequeuehandler mqh = new Messagequeuehandler();
			pPw.println(mqh.getMessages());
			pPw.flush();
			Chooser.choose(pBr.readLine(), pBr, pPw, pUser);
		} else if(msg[0].equals("QUIT") || msg[0].equals("EXIT")) {
			pPw.flush();
		} else {
			Chooser.choose(pBr.readLine(), pBr, pPw, pUser);
		}
	}
}
