package com.ejie.aa20b.informes;

import java.io.File;
import java.io.IOException;
import java.io.StringReader;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.sax.SAXResult;
import javax.xml.transform.stream.StreamSource;

import org.apache.fop.apps.FOPException;
import org.apache.fop.apps.FOUserAgent;
import org.apache.fop.apps.Fop;
import org.apache.fop.apps.FopFactory;
import org.apache.fop.apps.MimeConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;

public class t07bGeneraPDF_RTF {

	/**
	 * Construye el pdf con los datos del Expediente
	 * 
	 * @param request
	 *            HttpServletRequest
	 * @param response
	 *            HttpServletResponse
	 * @throws FOPException
	 * @throws TransformerException
	 * @throws IOException
	 * @throws Exception
	 */
	private static final Logger logger = LoggerFactory
			.getLogger(t07bGeneraPDF_RTF.class);

	public void generaFO2RTF(HttpServletRequest request,
			HttpServletResponse response, String ficheroFoString)
			throws FOPException, TransformerException {

		/* Init */
		FopFactory fopFactory = FopFactory.newInstance();
		FOUserAgent foUserAgent = fopFactory.newFOUserAgent();
		ServletOutputStream out = null;

		try {
			t07bGeneraPDF_RTF.logger.info("Genera RTF 1 : " + ficheroFoString);

			out = response.getOutputStream();

			response.setContentType(MimeConstants.MIME_RTF);
			Fop fop = fopFactory.newFop(MimeConstants.MIME_RTF, foUserAgent,
					out);

			// Setup JAXP using identity transformer
			TransformerFactory factory = TransformerFactory.newInstance();
			Transformer transformer = factory.newTransformer(); // identity
																// transformer

			StringReader reader = new StringReader(ficheroFoString);
			Source src = new StreamSource(reader);

			// Realizamos la transformación a .pdf
			Result res = new SAXResult(fop.getDefaultHandler());
			transformer.transform(src, res);
			t07bGeneraPDF_RTF.logger.info("Fin de la Generacion de RTF");
		} catch (Exception e) {
			e.printStackTrace(System.err);
			System.exit(-1);
		} finally {
			try {
				out.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}

	// Saca por pantalla el doc
	public void generarXML2RTF(HttpServletResponse response, Document doc,
			String plantilla)

	throws Exception {

		// FacesContext facesContext = FacesContext.getCurrentInstance();
		// ExternalContext externalContext = facesContext.getExternalContext();
		// String basePath = externalContext.getRealPath("/");
		String basePath = "";

		/******************/

		logger.info("Generando RTF....");

		/* Init */
		FopFactory fopFactory = FopFactory.newInstance();
		fopFactory.setBaseURL(basePath);
		FOUserAgent foUserAgent = fopFactory.newFOUserAgent();
		foUserAgent.setBaseURL(fopFactory.getBaseURL());
		ServletOutputStream out = null;

		try {

			out = response.getOutputStream();

			response.setContentType(MimeConstants.MIME_RTF);
			response.setHeader("Content-disposition",
					"attachment; filename=fichero.doc");
			Fop fop = fopFactory.newFop(MimeConstants.MIME_RTF, foUserAgent,
					out);

			// Setup JAXP using identity transformer
			TransformerFactory factory = TransformerFactory.newInstance();
			// Transformer transformer = factory.newTransformer(); // identity
			// transformer
			Transformer transformer = factory.newTransformer(new StreamSource(
					(new File(plantilla))));

			// Setup input for XSLT transformation
			transformer.setParameter("versionParam", "2.0");
			DOMSource src = new DOMSource(doc);

			// Realizamos la transformación a .pdf
			Result res = new SAXResult(fop.getDefaultHandler());

			transformer.transform(src, res);

			t07bGeneraPDF_RTF.logger.info("Fin de la Generacion de RTF");
		} catch (Exception e) {
			e.printStackTrace(System.err);
			System.exit(-1);
		} finally {
			try {
				out.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}

	// Saca por pantalla el doc
	public void generarXML2PDF(HttpServletResponse response, Document doc,
			String plantilla)

	throws Exception {

		logger.info("Generando pdf....");

		/* Init */
		FopFactory fopFactory = FopFactory.newInstance();
		FOUserAgent foUserAgent = fopFactory.newFOUserAgent();
		ServletOutputStream out = null;

		try {

			out = response.getOutputStream();

			response.setContentType(MimeConstants.MIME_PDF);
			response.addHeader("Content-Disposition",
					"attachment;filename=pdffile.pdf");
			Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, foUserAgent,
					out);

			// Setup JAXP using identity transformer
			TransformerFactory factory = TransformerFactory.newInstance();

			// Transformer transformer = factory.newTransformer(); // identity
			// transformer

			Transformer transformer = factory.newTransformer(new StreamSource(
					(new File(plantilla))));

			// Setup input for XSLT transformation
			transformer.setParameter("versionParam", "2.0");
			DOMSource src = new DOMSource(doc);

			// Realizamos la transformación a .pdf
			Result res = new SAXResult(fop.getDefaultHandler());

			transformer.transform(src, res);

			t07bGeneraPDF_RTF.logger.info("Fin de la Generacion de PDF");
		} catch (Exception e) {
			e.printStackTrace(System.err);
			System.exit(-1);
		} finally {
			try {
				out.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}

}
