package com.fp.frontend.servlet;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.StringWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringEscapeUtils;

import com.fp.frontend.controller.alfresco.AlfrescoController;

/**
 * Servlet que se encarga de abrir la ayuda
 *
 * @author WPA
 */
@WebServlet(name = "HelpServlet", urlPatterns = {"/HelpServlet"})
public class HelpServlet extends HttpServlet {

    private static final long serialVersionUID = 6934418044442466664L;
    private boolean shuttingDown = false;

    //Access methods for shuttingDown
    protected synchronized void setShuttingDown(boolean flag) {
        shuttingDown = flag;
    }

    protected synchronized boolean isShuttingDown() {
        return shuttingDown;
    }

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        OutputStream outputStream = response.getOutputStream();
        response.setContentType("text/html");
        try {
            response.setHeader("Pragma", "no-cache");

            String module = request.getParameter("cmodule");
            String transaction = request.getParameter("ctransaction");
//            String version = request.getParameter("version");
            String path = request.getParameter("path");
            String name = "cm:help_" + module + "_" + transaction + ".pdf";
            InputStream inputStream = AlfrescoController.getDocument(name, path);
            response.setContentType("application/pdf");

            if (inputStream != null) {

                IOUtils.copy(inputStream, outputStream);
                IOUtils.closeQuietly(inputStream);
                IOUtils.closeQuietly(outputStream);

                outputStream.flush();
            } else {
                PrintWriter printWriter = new PrintWriter(outputStream);
                printWriter.println("<html>");
                printWriter.println("<head>");
                printWriter.println("<title>Ayuda</title>");
                printWriter.println("</head>");
                printWriter.println("<body>");
                printWriter.println("<h1>Archivo " + name + ".pdf no disponible en el sistema</h1>");
                printWriter.println("</body>");
                printWriter.println("</html>");
                printWriter.write("<script type=\"text/javascript\">");
                printWriter.write("window.opener.mensajeAyuda('" + name + "');window.close();");
                printWriter.write("</script>");
                printWriter.close();
            }
        } catch (Throwable ex) {
            String mensaje = getStackTrace(ex);
            if (mensaje == null) {
                mensaje = "";
            }
            PrintWriter printWriter = new PrintWriter(outputStream);
            printWriter.println("<html>");
            printWriter.println("<head>");
            printWriter.println("<title>Ayuda</title>");
            printWriter.println("</head>");
            printWriter.println("<body>");
            printWriter.println("<h1>" + ex.getMessage() + "</h1>");
            printWriter.println("<pre style=\"width:100%;height:85%;overflow:auto;\">" + StringEscapeUtils.escapeHtml(mensaje) + "</pre>");
            printWriter.println("</body>");
            printWriter.println("</html>");
            printWriter.close();
        } finally {
            outputStream.close();
        }
    }

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

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

    /**
     * M&eacute;todo que devuelve la excepcion como tal
     *
     * @param ex
     * @return
     */
    public String getStackTrace(Throwable ex) {
        try {
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            if (ex.getCause() != null) {
                ex.getCause().printStackTrace(pw);
            } else {
                ex.printStackTrace(pw);
            }
            String data = sw.toString();
            pw.close();
            return data;
        } catch (Exception e) {
            return null;
        }
    }
}
