/*
 * This file is part of DebGen Biobank Software developed by ASTRID Research.
 * All rights reserved. Reproduction, modification, use or disclosure
 * to third parties without express authority is forbidden.
 *
 * Copyright ASTRID Research Inc., Hungary, 2009-2011.
 *
 * ASTRID Research
 * Headquaters: Csapo utca 42. Debrecen H-4029 HUNGARY
 * Phone: +36-52-533-173        Fax: +36-52-533-174
 * Web: http://www.astrid.hu    E-mail: info@astrid.hu
 *
 * Project name: DebGen Biobank Software project.
 * URLS:
 * Developers: Istvan Zoltan Nagy (istvan.nagy@astrid.hu)
 */
package hu.astrid.debgen.forgottenpassword.servlet;

import hu.astrid.debgen.exception.UserNotExistException;
import hu.astrid.debgen.forgottenpassword.facade.ForgottenPasswordFacade;
import hu.astrid.debgen.server.requestprocessor.ActionParameter;
import hu.astrid.debgen.server.requestprocessor.RequestTokenizer;
import org.apache.log4j.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Processes Forgotten password operations (reminders, cancel and confirm requests)
 * @author inagy
 */
public class ForgottenPasswordServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    /**
     * Logger
     */
    static Logger logger = Logger.getLogger(ForgottenPasswordServlet.class);

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        logger.debug("doPost() called.");
        ActionParameter actionParameter = ActionParameter.getActionParameter(request);
        logger.debug(actionParameter);
        logger.debug(RequestTokenizer.getRequestData(request));
        String action = actionParameter.getAction();
        try {
            if (action.equals("confirmpassword")) {               //Complete an order
                confirmPassword(request, response);
            } else if (action.equals("cancelpassword")) {
                cancelPassword(request, response);
            } else if (action.equals("sendreminder")) {
                sendReminder(request, response);
            }
//        } catch (AccessDeniedException ex) {
//            request.setAttribute("answer", true);
//            request.setAttribute("globalexception", new ServerSideException("Nincs jogosultsága kérés befejezéséhez."));
//            request.getRequestDispatcher("index.jsp").forward(request, response);
        } catch (Exception ex) {
            throw new ServletException(ex);
            //      request.setAttribute("answer", true);
            //      request.setAttribute("globalexception", new ServerSideException("A kért erőforrás nem található, vagy a hivatkozás hibás."));
            //      request.getRequestDispatcher("index.jsp").forward(request, response);
        }
    }

    /**
     * Send the password reminder message
     * @param request The HttpRequest of the operation.
     * @param response The HttpResponse of the operation.
     * @throws Exception When the operation is not possible.
     */
    private void sendReminder(HttpServletRequest request, HttpServletResponse response) throws Exception {
        logger.debug("sendReminder() called");
        String email = request.getParameter("email");
        ForgottenPasswordFacade facade = new ForgottenPasswordFacade();
        try {
            facade.requestNewPassword(email);
            response.sendRedirect("forgottenpassword.html?emailsent");
        } catch (UserNotExistException ex) {
            logger.error(ex);
            response.sendRedirect("forgottenpassword.html?noemailaddress");
        } catch (Exception ex) {
            logger.error(ex);
            throw ex;
        }

    }

    /**
     * Confirm the password reminder message
     * @param request The HttpRequest of the operation.
     * @param response The HttpResponse of the operation.
     * @throws Exception When the operation is not possible.
     */
    private void confirmPassword(HttpServletRequest request, HttpServletResponse response) throws Exception {
        logger.debug("confirmPassword() called");
        try {
            String userName = request.getParameter("userName");
            String confirmCode = request.getParameter("confirmCode");
            ForgottenPasswordFacade facade = new ForgottenPasswordFacade();
            facade.confirmPassword(userName, confirmCode);
            response.sendRedirect("login.html?action=login&username=" + userName + "&password=");
        } catch (UserNotExistException ex) {
            logger.error(ex);
            response.sendRedirect("forgottenpassword.html?confirmerror");
        } catch (Exception ex) {
            logger.error(ex);
            throw ex;
        }
    }

    /**
     * Cancel the password reminder message
     * @param request The HttpRequest of the operation.
     * @param response The HttpResponse of the operation.
     * @throws Exception When the operation is not possible.
     */
    private void cancelPassword(HttpServletRequest request, HttpServletResponse response) throws Exception {
        logger.debug("confirmPassword() called");
        try {
            String userName = request.getParameter("userName");
            String cancelCode = request.getParameter("cancelCode");
            ForgottenPasswordFacade facade = new ForgottenPasswordFacade();
            facade.cancelPassword(userName, cancelCode);
            response.sendRedirect("forgottenpassword.html?cancelled");
        } catch (UserNotExistException ex) {
            logger.error(ex);
            response.sendRedirect("forgottenpassword.html?cancelerror");
        } catch (Exception ex) {
            logger.error(ex);
            throw ex;
        }
    }
}
