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

import elements.Functions;
import hu.astrid.debgen.authentication.domain.DebGenUser;
import hu.astrid.debgen.authentication.exception.AccessDeniedException;
import hu.astrid.debgen.exception.ServerSideException;
import hu.astrid.debgen.patientmanagement.domain.modules.Result;
import hu.astrid.debgen.patientmanagement.domain.modules.requests.LabelList;
import hu.astrid.debgen.patientmanagement.facade.modules.ResultManagerFacade;
import hu.astrid.debgen.patientmanagement.facade.sample.SampleManagerFacade;
import hu.astrid.debgen.patientmanagement.servlet.PatientManagerServlet;
import hu.astrid.debgen.server.requestprocessor.ActionParameter;
import hu.astrid.debgen.server.requestprocessor.RequestTokenizer;
import hu.astrid.debgen.server.requestprocessor.facade.RequestProcessorFacade;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URI;
import java.text.SimpleDateFormat;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;

/**
 * Manages the print operations of result requests
 * @author inagy
 */
public class ModulePrintManagerServlet extends HttpServlet {

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

    protected void processResult(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("printmodule")) {
                createPrintResult(request, response);
            } else if (action.equals("moduleprint")) {
                doPrint(request, response);
            } else if (action.equals("generatepdfmodule")) {
                getPDF(request, response);
            } else if (action.equals("sendreprintmodule")) {
                rePrint(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);
        }

    }

    /**
     * Loads the needed data from the DB to setup a new print job
     * @param request
     * @param response
     * @throws Exception When DB fails or other failure occures
     */
    private void createPrintResult(HttpServletRequest request, HttpServletResponse response) throws Exception {
        logger.debug("createPrintResult() called.");
        ResultManagerFacade facade = new ResultManagerFacade();
        try {
            Long id = new Long(request.getParameter("module"));
            Result result = facade.loadResult(id);
            request.setAttribute("module", result);
            request.setAttribute("patient", result.getPatient());
            request.setAttribute("answer", true);
            request.getRequestDispatcher("index.jsp").forward(request, response);
        } catch (Exception ex) {
            logger.error(ex);
            throw ex;
        }
    }

    /**
     * Generates the needed files, and redirects to print applet
     * @param request
     * @param response
     * @throws Exception When DB fails or other failure occures
     */
    private void doPrint(HttpServletRequest request, HttpServletResponse response) throws Exception {
        logger.debug("doPrint() called.");
        request.setAttribute("answer", true);
        ResultManagerFacade facade = new ResultManagerFacade();
        int patientLabels = 0;
        try {
            Long id = new Long(request.getParameter("module"));
            Result result = facade.loadResult(id);
            request.getSession().setAttribute("lastPrintedPatient", result.getPatient().getId());
            DebGenUser user = RequestProcessorFacade.getDebGenUser(request);
            LabelList labelList = new LabelList();
            labelList.initializeLabels(request, result.getPatient().getPatientCode(), new SampleManagerFacade().listSampleTypes("oneLetterCode"));
            
            try {
                String value = Functions.encodeString(request.getParameter("patientCodeCopies"));
                patientLabels = Integer.parseInt(value);
            } catch (Exception ex) {
                //IGNORED
                logger.info("No correct patient code copy number found.");
            }
            URI uri = facade.generatePDF(result, user, patientLabels);
            request.setAttribute("file", "printjobs/" + new File(uri).getName());
            request.setAttribute("copies", request.getParameter("pdfCopies"));
            /*
             * TODO kicserélni a nyomtató nevét!!!
             */
            request.setAttribute("printer", "Cups-PDF");
            request.getRequestDispatcher("index.jsp").forward(request, response);
        } catch (Exception ex) {
            logger.error(ex);
            throw ex;
        }
    }

    /**
     * Redirects to print applet
     * @param request
     * @param response
     * @throws Exception When the redirect fails or other failure occures
     */
    private void rePrint(HttpServletRequest request, HttpServletResponse response) throws Exception {
        request.setAttribute("file", request.getParameter("pdf"));
        request.setAttribute("copies", request.getParameter("copies"));
        request.setAttribute("answer", true);
        /*
         * TODO kicserélni a nyomtató nevét!!!
         */
        request.setAttribute("printer", "Cups-PDF");
        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 {
        processResult(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 {
        processResult(request, response);


    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";

    }// </editor-fold>

    /**
     * Puts the pdf to the stream
     * @param request
     * @param response
     * @throws Exception When the redirect fails or other failure occures
     */
    private void getPDF(HttpServletRequest request, HttpServletResponse response) throws Exception {
        logger.debug("getPDF() called.");
        request.setAttribute("answer", true);
        ResultManagerFacade facade = new ResultManagerFacade();
        Long id = new Long(request.getParameter("module"));
        Result result = facade.loadResult(id);
        DebGenUser user = RequestProcessorFacade.getDebGenUser(request);
        URI uri = facade.generatePDF(result, user, 0);
        File file = null;
        file = new File(uri);
        file.deleteOnExit();
        FileInputStream in = null;
        ServletOutputStream out = null;
        byte[] b = new byte[1024];
        int read = 0;
        try {
            in = new FileInputStream(file);
            out = response.getOutputStream();
            response.setContentType("application/pdf");
            response.setHeader("Content-Disposition", "attachment; filename=\"DebGen_" + result.getPatient().getPatientCode() + "_" + new SimpleDateFormat("yyyy-MM-dd").format(result.getCreatedOn()) + "_" + Long.toHexString(result.getId()) + "-2.pdf\"");
            response.setHeader("Content-Length", file.length() + "");
            while ((read = in.read(b)) != -1) {
                out.write(b, 0, read);
            }
        } catch (IOException ex) {
            throw ex;
        } finally {
            try {
                out.close();
            } catch (IOException iOException) {
                //IGNORED
            }
            try {
                in.close();
            } catch (IOException iOException) {
                //IGNORED
            }
            boolean deleted = file.delete();
            if (!deleted) {
                logger.error("Can't delete file: " + file.getAbsolutePath());
            }
        }
    }
}
