// A. Toy, A10 for CISC474, Spring 2006
// LoginSelect class
// Modified: 5/8/06

package com.gmscheduler.web;

import com.gmscheduler.model.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;

public class LoginSelect extends HttpServlet {

  public void doPost(HttpServletRequest request,
			HttpServletResponse response)
		throws IOException, ServletException {
    DatabaseManager dm = new DatabaseManager();
    //LoginExpert le = new LoginExpert();
    Person p = new Person();
    String user = "";
    String password = "";
    boolean success = false;

    //create new user
    if(request.getParameter("newpassword") != null)
    {
      user = request.getParameter("user");
      password = request.getParameter("password");
      String newpassword = request.getParameter("newpassword");

      if(password.compareTo(newpassword) == 0) {
    	p.setName(user);
    	p.setPassword(password);
        p = dm.storePerson(p);
        success = true;
      }
      else	{//user entered two new passwords 
         success = false;
      }
    }

    //else log in existing user
    else
    {
      user = request.getParameter("user");
      if(user.length() > 0)
      {
        password = request.getParameter("password");
        p = dm.loadPersonByName(user);
        success = p.isValidPassword(password);
      }
      else
        success = false;
    }

    request.setAttribute("user", user);
    request.setAttribute("password", password);
    request.setAttribute("success", success);

    RequestDispatcher view = request.getRequestDispatcher("mainmenu.jsp");

    view.forward(request, response);
  }
}

