/**************************************************
  This servlet gets login information from the user.  If the information is a valid and verified
  account, the user is forwarded to the main menu of the program.  Otherwise, the user is sent back
  to the login screen with an appropriate error message.
 
  @author Anthony Furst
  @version CISC474 A10
*/

package com.example.web;

import com.example.model.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.lang.*;
import java.io.*;
import java.util.*;
import java.sql.*;

public class LoginValidate extends HttpServlet {
  
    /** Performs all functionality of the servlet
	@param request A servlet request object
	@param response A servlet response object
    */
    public void doPost(HttpServletRequest request,
		       HttpServletResponse response)
	throws IOException, ServletException {
	String username;
	String password;
	String url;

	username = getServletContext().getInitParameter("user");
	password = getServletContext().getInitParameter("passwd");
	url = getServletContext().getInitParameter("url");

	Validator validate = new Validator();

	String name = request.getParameter("username");
	String pw = request.getParameter("password");
	boolean validLogin = true;
	boolean verifiedLogin = false;

	validate.makeConnection(username, password, url);
	validLogin = validate.validAccount(name, pw);	

	if (validLogin) {
	    verifiedLogin = validate.verifiedAccount(name, pw);

	    //Valid, Verified login information
	    if (verifiedLogin) {
		validate.closer();
		
		request.setAttribute("user", name);
		RequestDispatcher view = request.getRequestDispatcher("menu.jsp");
		view.forward(request, response);
	    }
	    //Valid, non-verified login information
	    else {
		validate.closer();

		request.setAttribute("reason", "notVerified");
		RequestDispatcher view = request.getRequestDispatcher("loginError.jsp");
		view.forward(request, response);
	    }
	}
	//Non-valid login information
	else {
	    validate.closer();
	    
	    request.setAttribute("reason", "invalid");
	    RequestDispatcher view = request.getRequestDispatcher("loginError.jsp");
	    view.forward(request, response);
	}
    }
}
