/*
 * 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.server.requestprocessor.servlet;

import hu.astrid.debgen.server.requestprocessor.*;
import hu.astrid.debgen.exception.ServerSideException;
import hu.astrid.debgen.server.requestprocessor.exception.InvalidPageNameFormatException;
import hu.astrid.debgen.server.requestprocessor.facade.RequestProcessorFacade;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import org.apache.log4j.Logger;

public class RequestProcessorServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    /**
     * Logger
     */
    private static final Logger logger =
            Logger.getLogger(RequestProcessorServlet.class);

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

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ActionParameter actionParameter = null;
        try {
            String requestedPage = (String) request.getAttribute("requestedPage");
            actionParameter = RequestProcessorFacade.getActionParameterFromUri(requestedPage);
            boolean changePassword = request.getSession().getAttribute("passwordchange") != null &&
                    request.getSession().getAttribute("passwordchange").equals(true);
            String action = actionParameter.getAction();
            String[] allowedPagesWithoutPasswordChange = {"changepassword", "logout"}; //savepassword
            if (!ActionParameter.in(action, allowedPagesWithoutPasswordChange) && changePassword) {
                response.sendRedirect("changepassword.html");
                return;
            }

            String info = (String) request.getAttribute("informationString");
            if (info != null) {
                logger.debug("INFO message: " + info);
                actionParameter = ActionParameter.getInformationActionParameter();
            }
            Exception ex = (Exception) request.getAttribute("exception");
            if (ex != null) {
                actionParameter.setException(ex);
                actionParameter.setErrorMessage(ex.getMessage());
                if (ex instanceof ServerSideException) {
                    ServerSideException sex = (ServerSideException) ex;
                    actionParameter.setErrorMessage(sex.getMessage());
                    actionParameter.setException(sex.getNestedException());
                }
            }

            request.setAttribute("actionParameter", actionParameter);
        } catch (InvalidPageNameFormatException e) {
            request.setAttribute("actionParameter", ActionParameter.getInvalidPageActionParameter(e));
        } catch (Exception ex) {
            throw new ServletException(ex);
        }
        logger.debug("Requested page - action parameter: [" + actionParameter + "] - answer: [" + (request.getAttribute("answer") == null ? "false" : "true") + "]");
        if (!actionParameter.getScope().equals("default") && request.getAttribute("answer") == null) {
            request.getRequestDispatcher(actionParameter.getScope() + ".do").forward(request, response);
            return;
        } else {
            request.getRequestDispatcher("main.jsp").forward(request, response);
            return;
        }
    }
}
