package server.servlets;

import javax.servlet.ServletException;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Login Class
 */

public class Login extends HttpServlet {

    /**
     * First call to this sevlet retuns the Login Page. Subsequent calls
     * validate the userId and password. If entries are valid then the
     * process is redirected to FormC Servlet
     * @throws    IOException ServletException
     */

    public void doGet(HttpServletRequest request,
                      HttpServletResponse response)
            throws IOException, ServletException {

        response.setContentType("text/html");
        PrintWriter out = response.getWriter();

        HttpSession session = request.getSession(true);
        LoginProcess login = (LoginProcess) session.getValue("login");

        if (session.isNew() || login == null) {
            login = new LoginProcess();

            Cookie loginCookie = new Cookie("Login", "LoginPage");
            response.addCookie(loginCookie);

            session.putValue("login", login);
            out.println(login.getLoginPage());
        } else {
            String user = request.getParameter("txtUserId");
            String password = request.getParameter("txtPassword");

            System.out.println("\n Cookie Example");
            System.out.println("\n Cookie Login = " +
                    RequestUtil.getCookieValue(request.getCookies(), "Login"));

            if (login.isValid(user, password)) {
                session.putValue("userId", user);
                session.putValue("nextAction", "FormC");
                response.sendRedirect(login.getLoginRedirectURL());
            } else {
                out.println(login.getLoginErrorPage());
            }
        }
    }


    /**
     * Calls doGet() method
     *
     * @throws    IOException ServletException
     */

    public void doPost(HttpServletRequest request,
                       HttpServletResponse response)
            throws IOException, ServletException {

        doGet(request, response);

    }

}