package chat.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import chat.*;

/**
@author Sukhwinder Singh
*/
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private String contextPath = "";
	/** This method just redirects user to a login page.*/
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		contextPath = request.getContextPath();
		response.sendRedirect(contextPath + "/login.jsp");		
	}
	/** Performs some validation and if everything is ok sends user to a page which displays a list of
	* rooms available.
	*/
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		contextPath = request.getContextPath();		
		/*
		String nickname = request.getParameter("nickname");
		nickname = nickname.trim();
		String team = request.getParameter("team");
		if (team.length() > 0) {
			team = team.trim();
		}
		*/
		String rawValue = request.getParameter("team");
		String[] fields = rawValue.split("/");
		String nickname = fields[0];
		String team = fields[1];
		if ((nickname != null && nickname.length() > 2 && nickname.indexOf(" ") == -1) && (team != null)) {
			try	{
				ChatRoomList roomlist = (ChatRoomList)getServletContext().getAttribute("chatroomlist");
				boolean chatterexists = roomlist.chatterExists(nickname);
				if (chatterexists) {
					response.sendRedirect(contextPath + "/login.jsp?d=t&n="+nickname);
				}
				else {
					HttpSession session = request.getSession(true);
					int timeout = 1800; // 30 minutes
					String t = getServletContext().getInitParameter("sessionTimeout"); // gets Minutes
					if (t != null) {
						try	{
							timeout = Integer.parseInt(t);
							timeout = timeout * 60;
						} catch (NumberFormatException nfe)	{							
						}
					}
					session.setMaxInactiveInterval(timeout);
					session.setAttribute("nickname", nickname);
					ChatRoom chatRoom = roomlist.getMainRoom();
					Chatter chatter = null;
					chatter = new Chatter(nickname, team, new java.util.Date().getTime());
					chatRoom.addChatter(chatter);
					chatRoom.addMessage(new Message("system", nickname + " has joined.", new java.util.Date().getTime()));
					chatter.setEnteredInRoomAt(new java.util.Date().getTime());
					response.sendRedirect(contextPath + "/chat.jsp");

				}
			} catch(Exception exception) {
				System.out.println("Exception thrown in LoginServlet: " + exception.getMessage());
				exception.printStackTrace();
				response.sendRedirect(contextPath + "/error.jsp");
			}
		} else {
			response.sendRedirect(contextPath + "/login.jsp?ic=t");
		}
	}
}