package ajax;

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

import javax.servlet.*;
import javax.servlet.http.*;
import javax.persistence.EntityManager;

// Our classes
import ajax.database.UserAccountNotFoundException;
import ajax.database.UserBean;
import ajax.database.User;

/**
 * Main control servlet
 *
 * @author Adam J. Kaplan
 */
public class Controller extends HttpServlet 
{
	private static final long serialVersionUID = 1L;
	private HttpServletRequest request;
	private HttpServletResponse response;

	/**
	* Get method handler for servlet functionality.
	* 
	* @param request The HTTP request to the servlet
	* @param response The HTTP response to the client
	*/
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException
	{
		this.request = request;
		this.response = response;
		dispatchRequest();
	}

	/**
	* Post method handler for servlet functionality.
	* 
	* @param request The HTTP request to the servlet
	* @param response The HTTP response to the client
	* @see #doGet
	*/
	public void doPost(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException
	{ doGet(request, response); }

	/* Dispatch request to the appripriate bean or whatever */
	private void dispatchRequest() throws ServletException, IOException
	{	
		String op = this.request.getParameter("op");
		if (op == null) { // new user, fresh request
			forward("index.jsp");
		}
		else if (op.equals("login")) { // requesting login
			action_Login();
		}
		else if (op.equals("chat")) { // chat functions
			action_Chat();
		}
		else if (op.equals("heartbeat")) {
			action_Heartbeat();
		}
		else if (op.equals("logout")) { // log out, squish session
			request.getSession().invalidate();
			request.getSession();
			request.setAttribute("message", 
					"You have been successfully logged out.");
			request.setAttribute("msgLevel", "msgInfo");
			forward("index.jsp");
		}
		else {
			request.setAttribute("message", "An Error Has Occured");
			request.setAttribute("msgLevel", "msgCrit");
			forward("error.jsp");
		}
	}

	/** Attempt to log a user in 
	 * @throws ServletException 
	 * @throws IOException 
	 */
	private void action_Login() throws IOException, ServletException
	{
		String name = request.getParameter("lname");
		String pass = request.getParameter("lemail");

		if (!valid(name) || !valid(pass)) {
			forward("error.jsp");
			return;
		} 
		
		User u;
		try { 
			u = UserBean.findUser(name);
			if (!u.validateCredentials(pass)) {
				request.setAttribute("message", 
						"invalid username/password combination");
				request.setAttribute("msglevel", "msgwarn");
				forward("index.jsp");
				return;
			}
		}
		catch (UserAccountNotFoundException e)
		{
			u = UserBean.registerUser(name, pass);
		}
		catch (Exception e)
		{
			request.setAttribute("message", e.getMessage());
			request.setAttribute("msglevel", "msgcrit");
			forward("error.jsp");
			return;
		}
		request.getSession().setAttribute("user_obj", u);
		forward("panel.jsp");
	}
	
	/** chat mode operations 
	 * @throws ServletException 
	 * @throws IOException */
	private void action_Chat() throws IOException, ServletException
	{
		HttpSession session = request.getSession(false);
		if (session.getAttribute("user_obj") == null) {
			request.setAttribute("message", "you need to log in.");
			request.setAttribute("msglevel", "msgwarn");
			forward("index.jsp");
			return;
		}
		
		String toUserId = request.getParameter("to");
		if (!valid(toUserId)) {
			request.setAttribute("message", "invalid recipiant specified.");
			request.setAttribute("msglevel", "msgcrit");
			forward("error.jsp");
			return;
		}
		
		User toUser;
		try { 
			toUser = UserBean.findUser(Integer.valueOf(toUserId));
		}
		catch (Exception e)
		{
			request.setAttribute("message", e.getMessage());
			request.setAttribute("msglevel", "msgcrit");
			forward("error.jsp");
			return;
		}
		session.setAttribute("chat_target", toUser);
		forward("chat.jsp");
	}
	
	private void action_Heartbeat() throws IOException, ServletException
	{
		HttpSession session = request.getSession(false);
		if (session.getAttribute("user_obj") == null) {
			request.setAttribute("message", "you need to log in.");
			request.setAttribute("msglevel", "msgwarn");
			forward("index.jsp");
			return;
		}
		
		// get a handle to the persistent object from the entity manager
		User user = UserBean.getPersistentHandle(session.getAttribute("user_obj"));
		//user.setUsername("tim2");
		Date h1 = user.getLast_heartbeat();
		user.setLast_heartbeat(new Date());
		request.setAttribute("message", "times: " + h1
							+ " : " + user.getLast_heartbeat());
		request.setAttribute("msglevel", "msgwarn");
		forward("error.jsp");
	}
	
	/* private helper methods only below this point */
	private void forward(String url) 
		throws java.io.IOException, ServletException
	{
		RequestDispatcher rd = this.request.getRequestDispatcher(url);
		rd.forward(this.request, this.response);
	}
	
	private boolean valid(String s) { return (s != null && s.length() > 0); }
}

