/*
 * 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.sample;

import hu.astrid.debgen.authentication.exception.AccessDeniedException;
import hu.astrid.debgen.exception.ServerSideException;
import hu.astrid.debgen.exception.ValidationFailedException;
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.sample.SampleType;
import hu.astrid.debgen.patientmanagement.facade.sample.SampleManagerFacade;
import java.io.IOException;
import java.util.List;
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 SampleManagerServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;
    static Logger logger = Logger.getLogger(SampleManagerServlet.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("listsampletypes")) {
                listSampleTypes(request, response);
            } else if (action.equals("savesampletype")) {
                saveSampleType(request, response);
            } else if (action.equals("deletesampletype")) {
                deleteSampleType(request, response);
            } else if (action.equals("showsample")) {
                showSample(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="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>

    // <editor-fold defaultstate="collapsed" desc="SampleType">
    /**
     * Lists the SampleTypes
     * @param request
     * @param response
     */
    private void listSampleTypes(HttpServletRequest request, HttpServletResponse response) throws ServerSideException, Exception {
        logger.debug("listSampleTypes() called.");
        List<SampleType> sampleTypes = null;
        try {
            DebGenUser user = RequestProcessorFacade.getDebGenUser(request);
            SampleManagerFacade facade = new SampleManagerFacade();
            if (user.isDataRecorder() || user.isResearcher()) {
                sampleTypes = facade.listSampleTypes("oneLetterCode");
            } else {
                throw new ServerSideException("HOZZÁFÉRÉS_MEGTAGADVA!_NEM_RENDELKEZIK_A_FUNKCIÓ_ELÉRÉSÉHEZ_SZÜKSÉGES_JOGOSULTSÁGGAL!");
            }
            request.setAttribute("samples", sampleTypes);
            request.setAttribute("answer", true);
            request.getRequestDispatcher("index.jsp").forward(request, response);
        } catch (Exception ex) {
            logger.error(ex);
            throw ex;
        }
    }

    /**
     * Saves a new or modifies an old sampleType
     * @param request
     * @param response
     */
    private void saveSampleType(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, Exception {
        logger.debug("saveSampleType() called.");
        request.setAttribute("answer", true);
        try {
            boolean newType = false;
            Long id = 0L;
            SampleType sampleType = null;
            SampleManagerFacade facade = new SampleManagerFacade();
            try {
                id = new Long(request.getParameter("id"));
                sampleType = facade.loadSampleType(id);
            } catch (Exception ex) {
                //IGNORED, parameters can be empty
                logger.debug("New sampletype found, no problem!");
            }
            if (sampleType == null) {
                sampleType = new SampleType();
                newType = true;
            }
            sampleType.convert(request);
            sampleType.setOneLetterCode(sampleType.getOneLetterCode().toUpperCase());
            if (newType) {
                request.setAttribute("sample", sampleType);
            }
            sampleType.validate();
            facade.createOrModifySampleType(sampleType);
            request.setAttribute("info", "SIKERES_MENTÉS");
            //Pillanatnyilag nem volt jobb ötletem a kétszeres megírás elkerülésére...
            this.listSampleTypes(request, response);
        } catch (ValidationFailedException ex) {
            logger.error(ex);
            request.setAttribute("exception", new ServerSideException(ex));
            //Pillanatnyilag nem volt jobb ötletem a kétszeres megírás elkerülésére...
            this.listSampleTypes(request, response);
        } catch (ConstraintViolationException ex) {
            logger.error(ex);
            request.setAttribute("exception", new ServerSideException("MINTA_TIPUS_NEM_EGYEDI"));
            //Pillanatnyilag nem volt jobb ötletem a kétszeres megírás elkerülésére...
            this.listSampleTypes(request, response);
        } catch (Exception ex) {
            logger.error(ex);
            throw ex;
        }
    }

    /**
     * Deletes a sampleType
     * @param request
     * @param response
     */
    private void deleteSampleType(HttpServletRequest request, HttpServletResponse response) throws Exception {
        logger.debug("deleteSampleType() called.");
        try {
            Long id = new Long(request.getParameter("sample"));
            SampleManagerFacade facade = new SampleManagerFacade();
            facade.deleteSampleType(id);
            response.sendRedirect("listsampletypes.html");
        } catch (Exception ex) {
            logger.error(ex);
            throw ex;
        }
    }// </editor-fold>

    private void showSample(HttpServletRequest request, HttpServletResponse response) throws Exception {
        logger.debug("showSample() called.");
        request.setAttribute("answer", true);
        try {
            Long id = new Long(request.getParameter("sample"));
            SampleManagerFacade facade = new SampleManagerFacade();
            request.setAttribute("sample", facade.loadSample(id));
            request.getRequestDispatcher("index.jsp").forward(request, response);
        } catch (Exception ex) {
            logger.error(ex);
            throw ex;
        }
    }
}
