/*
 * 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.patientmanagement.servlet.modules.requests;

import elements.Functions;
import hu.astrid.debgen.authentication.exception.AccessDeniedException;
import hu.astrid.debgen.exception.ServerSideException;
import hu.astrid.debgen.exception.ValidationFailedException;
import hu.astrid.debgen.patientmanagement.facade.PatientManagerFacade;
import hu.astrid.debgen.server.requestprocessor.ActionParameter;
import hu.astrid.debgen.server.requestprocessor.RequestTokenizer;
import hu.astrid.debgen.server.requestprocessor.facade.RequestProcessorFacade;
import hu.astrid.debgen.authentication.domain.DebGenUser;
import hu.astrid.debgen.patientmanagement.domain.modules.requests.AnalysisRequest;
import hu.astrid.debgen.patientmanagement.domain.modules.requests.AnalysisRequestBornDefect;
import hu.astrid.debgen.patientmanagement.domain.modules.requests.AnalysisRequestOnkohaematology;
import hu.astrid.debgen.patientmanagement.domain.Patient;
import hu.astrid.debgen.patientmanagement.facade.modules.requests.RequestManagerFacade;
import hu.astrid.debgen.patientmanagement.facade.sample.SampleManagerFacade;
import java.io.IOException;
import java.text.SimpleDateFormat;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.hibernate.exception.ConstraintViolationException;

/**
 * Handles the operations with patients
 * @author inagy
 */
public class RequestManagerServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;
    static Logger logger = Logger.getLogger(RequestManagerServlet.class);

    protected void processRequest(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 {
            DebGenUser user = RequestProcessorFacade.getDebGenUser(request);
            if (!user.isDataRecorder() && !user.isResearcher()) {
                throw new AccessDeniedException();
            }
            if (action.equals("createrequest")) {
                editAnalysisRequest(request, response);
            } else if (action.equals("editrequest")) {
                editAnalysisRequest(request, response);
            } else if (action.equals("saverequest")) {
                saveAnalysisRequest(request, response);
            } else if (action.equals("showrequest")) {
                showAnalysisRequest(request, response);
            } else {
                request.setAttribute("answer", true);
                request.getRequestDispatcher("index.jsp").forward(request, response);
            }
        } catch (AccessDeniedException ex) {
            request.setAttribute("answer", true);
            request.setAttribute("globalexception", new ServerSideException("Nincs jogosultsága a kérés befejezéséhez."));
            request.getRequestDispatcher("index.jsp").forward(request, response);
        } catch (Exception 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);
        }

    }

    
    // <editor-fold defaultstate="collapsed" desc="Analysis request">
    /**
     * Tries to load an existing Analysis request object from the DB if necessary, or does nothing
     * @param request
     * @param response
     * @throws Exception When DB fails or other failure occures
     */
    private void editAnalysisRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
        logger.debug("editAnalysisRequest() called.");
        RequestManagerFacade facade = new RequestManagerFacade();
        try {
            Long id = new Long(request.getParameter("request"));
            AnalysisRequest analysis = facade.loadRequest(id);
            request.setAttribute("request", analysis);
            request.setAttribute("patient", analysis.getPatient());
            request.setAttribute("labels", new SampleManagerFacade().listSampleTypes("oneLetterCode"));
            request.setAttribute("answer", true);
            request.getRequestDispatcher("index.jsp").forward(request, response);
        } catch (Exception ex) {
            try {
                Long id = new Long(request.getParameter("patient"));
                Patient patient = new PatientManagerFacade().loadPatient(id);
                request.setAttribute("patient", patient);
                request.setAttribute("labels", new SampleManagerFacade().listSampleTypes("oneLetterCode"));
                request.setAttribute("answer", true);
                request.getRequestDispatcher("index.jsp").forward(request, response);
            } catch (Exception e) {
                logger.error(e);
                throw e;
            }
        }
    }

    /**
     * Saves an Analysis request object to the DB if possible
     * @param request
     * @param response
     * @throws Exception When DB fails or other failure occures
     */
    private void saveAnalysisRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
        logger.debug("saveAnalysisRequest() called.");
        request.setAttribute("answer", true);
        try {
            Long id = 0L;
            Long patient = 0L;
            AnalysisRequest analysis = null;
            RequestManagerFacade facade = new RequestManagerFacade();
            boolean newAnalysis = false;
            try {
                id = new Long(request.getParameter("id"));
                analysis = facade.loadRequest(id);
            } catch (Exception ex) {
                //IGNORED, parameters can be empty
                logger.debug("New request found, no problem!");
            }
            patient = new Long(request.getParameter("patient"));
            if (analysis == null) {
                newAnalysis = true;
                analysis = AnalysisRequest.getInstance(Functions.encodeString(request.getParameter("objectType")));
            }
            analysis.convert(request);
            try {
                analysis.setDateOfSampleArrival(new SimpleDateFormat("yyyy. MM. dd.").parse(Functions.encodeString(request.getParameter("dateOfSampleArrival"))));
            } catch (Exception e) {
                //IGNORED
                logger.debug("Unknown date format found! The datepicker is not set correctly, or the field is empty? " + request.getParameter("dateOfSampleArrival"));
            }
            try {
                analysis.setDateOfSampleProcessing(new SimpleDateFormat("yyyy. MM. dd.").parse(Functions.encodeString(request.getParameter("dateOfSampleProcessing"))));
            } catch (Exception e) {
                //IGNORED
                logger.debug("Unknown date format found! The datepicker is not set correctly, or the field is empty? " + request.getParameter("dateOfSampleProcessing"));
            }
            try {
                analysis.setStartOfTherapy(new SimpleDateFormat("yyyy. MM. dd.").parse(Functions.encodeString(request.getParameter("startOfTherapy"))));
            } catch (Exception e) {
                //IGNORED
                logger.debug("Unknown date format found! The datepicker is not set correctly, or the field is empty? " + request.getParameter("startOfTherapy"));
            }
            if (analysis instanceof AnalysisRequestBornDefect) {
                AnalysisRequestBornDefect bd = (AnalysisRequestBornDefect) analysis;
                try {
                    bd.setBdDNAStoredSampleDate(new SimpleDateFormat("yyyy. MM. dd.").parse(Functions.encodeString(request.getParameter("bdDNAStoredSampleDate"))));
                    bd.setBdDNAStoredSample(true);
                } catch (Exception e) {
                    //IGNORED
                    logger.debug("Unknown date format found! The datepicker is not set correctly, or the field is empty? " + request.getParameter("bdDNAStoredSampleDate"));
                }
            }
            if (analysis instanceof AnalysisRequestOnkohaematology) {
                AnalysisRequestOnkohaematology on = (AnalysisRequestOnkohaematology) analysis;
                try {
                    on.setOnDNAStoredSampleDate(new SimpleDateFormat("yyyy. MM. dd.").parse(Functions.encodeString(request.getParameter("onDNAStoredSampleDate"))));
                    on.setOnDNAStoredSample(true);
                } catch (Exception e) {
                    //IGNORED
                    logger.debug("Unknown date format found! The datepicker is not set correctly, or the field is empty? " + request.getParameter("onDNAStoredSampleDate"));
                }
                try {
                    if (!on.isOnCitFirst()) {
                        on.setOnCitPreviousDate(new SimpleDateFormat("yyyy. MM. dd.").parse(Functions.encodeString(request.getParameter("onCitPreviousDate"))));
                    } else {
                        on.setOnCitPreviousResult("");
                    }
                } catch (Exception e) {
                    //IGNORED
                    logger.debug("Unknown date format found! The datepicker is not set correctly, or the field is empty? " + request.getParameter("onCitPreviousDate"));
                }
                try {
                    if (!on.isOnFishFirst()) {
                        on.setOnFishPreviousDate(new SimpleDateFormat("yyyy. MM. dd.").parse(Functions.encodeString(request.getParameter("onFishPreviousDate"))));
                    } else {
                        on.setOnFishPreviousResult("");
                    }
                } catch (Exception e) {
                    //IGNORED
                    logger.debug("Unknown date format found! The datepicker is not set correctly, or the field is empty? " + request.getParameter("onFishPreviousDate"));
                }
            }
            analysis.setPatient(new PatientManagerFacade().loadPatient(patient));
            if (newAnalysis) {
                analysis.getPatient().addAnalysis(analysis);
            }
            request.setAttribute("labels", new SampleManagerFacade().listSampleTypes("oneLetterCode"));
            request.setAttribute("request", analysis);
            request.setAttribute("patient", analysis.getPatient());
            analysis.validate();
            facade.createOrModifyRequest(analysis);
            if (request.getParameter("send").contains(" ")) {
                response.sendRedirect("printrequest.html?request=" + analysis.getId());
            } else {
                response.sendRedirect("showpatient.html?patient=" + patient);
            }
        } catch (ValidationFailedException ex) {
            logger.error(ex);
            request.setAttribute("exception", new ServerSideException(ex));
            request.getRequestDispatcher("index.jsp").forward(request, response);
        } catch (ConstraintViolationException ex) {
            logger.error(ex);
            request.setAttribute("exception", new ServerSideException("Nem mentheti a beteget ezzel az azonosítóval, mert az azonosító már foglalt. Kérem válasszon másikat."));
            request.getRequestDispatcher("index.jsp").forward(request, response);
        } catch (Exception ex) {
            logger.error(ex);
            throw ex;
        }
    }

    /**
     * Loads a analysis request object from the DB if possible
     * @param request
     * @param response
     * @throws Exception When DB fails or other failure occures
     */
    private void showAnalysisRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
        logger.debug("showAnalysisRequest() called.");
        try {
            Long id = new Long(request.getParameter("request"));
            RequestManagerFacade facade = new RequestManagerFacade();
            AnalysisRequest analysis = facade.loadRequest(id);
            request.setAttribute("request", analysis);
            request.setAttribute("patient", analysis.getPatient());
            request.setAttribute("labels", new SampleManagerFacade().listSampleTypes("oneLetterCode"));
            request.setAttribute("answer", true);
            request.getRequestDispatcher("index.jsp").forward(request, response);
        } catch (Exception ex) {
            logger.error(ex);
            throw ex;
        }
    }// </editor-fold>

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
