package m05bClasses;

/* Fecha Creacion 18/01/2006 */

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.apache.fop.apps.Driver;
import org.apache.fop.apps.FOPException;
import org.xml.sax.InputSource;

/**
 * Clase que define la salida del Log en un fichero definido en la configuracion
 * de la aplicacion.
 */
public class m05bInformes {

	String sFoFileDir = "/datos/m05b/tmp/";

	File tmpFoFile, foFileDir;

	FileOutputStream tmpFoFileStream;

	String sLinea;

	m05bComun miComun = new m05bComun();

	m05bFileLog miLog = new m05bFileLog();

	public FileOutputStream fncAbrirFicheroTemporal()
			throws java.io.IOException {
		foFileDir = new File(sFoFileDir);
		tmpFoFile = File.createTempFile("m05b", "Fo", foFileDir);
		return tmpFoFileStream = new FileOutputStream(tmpFoFile);
	} // Fin funcion fncAbrirFicheroTemporal

	public void fncGenerarLayoutFin(FileOutputStream tmpFoFileStream,
			Integer nLinBefore) throws java.io.IOException {
		String sLinea = "";
		if (nLinBefore == m05bConstantesInformes.NUM_LINEAS_1) {
			sLinea = "		<fo:region-before extent=\"2cm\"/>\n";
			tmpFoFileStream.write(sLinea.getBytes());
			sLinea = "		<fo:region-body  margin-top=\"2cm\" margin-bottom=\"2cm\" />\n";
		} else if (nLinBefore == m05bConstantesInformes.NUM_LINEAS_2) {
			sLinea = "		<fo:region-before extent=\"4cm\"/>\n";
			tmpFoFileStream.write(sLinea.getBytes());
			sLinea = "		<fo:region-body  margin-top=\"3cm\" margin-bottom=\"2cm\" />\n";
		} else if (nLinBefore == m05bConstantesInformes.NUM_LINEAS_4) {
			sLinea = "		<fo:region-before extent=\"3cm\"/>\n";
			tmpFoFileStream.write(sLinea.getBytes());
			sLinea = "		<fo:region-body  margin-top=\"3.8cm\" margin-bottom=\"2cm\" />\n";
		}
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "		<fo:region-after  extent=\"2cm\"/>\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "		<fo:region-start extent=\"0cm\"/>\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "		<fo:region-end extent=\"0cm\"/>\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "	</fo:simple-page-master>\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "</fo:layout-master-set>\n";
		tmpFoFileStream.write(sLinea.getBytes());
	} // Fin funcion fncGenerarLayoutFin

	public void fncGenerarLayout(FileOutputStream tmpFoFileStream, String dir,
			Integer nLinBefore) throws java.io.IOException {
		String sLinea = "";
		sLinea = "<fo:layout-master-set>\n";
		tmpFoFileStream.write(sLinea.getBytes());
		miLog.addTraza("", "", "DIRECCION: " + dir,
				m05bConstantes.LOG_NIVEL_BAJO);
		if (dir.equals(m05bConstantesInformes.DIR_HORIZONTAL))
			sLinea = "	<fo:simple-page-master master-name=\"general\"  page-height=\"29.5cm\" page-width=\"21cm\" margin-top=\"2cm\" margin-bottom=\"2cm\" margin-left=\"2.5cm\" margin-right=\"2.5cm\">\n";
		else
			sLinea = "	<fo:simple-page-master master-name=\"general\"  page-height=\"29.5cm\" page-width=\"21cm\" margin-top=\"2cm\" margin-bottom=\"2cm\" margin-left=\"2.5cm\" margin-right=\"2.5cm\">\n";
		tmpFoFileStream.write(sLinea.getBytes());
		fncGenerarLayoutFin(tmpFoFileStream, nLinBefore);
	} // Fin funcion fncGenerarLayout

	public void fncGenerarTitulo(FileOutputStream tmpFoFileStream,
			String texto, String param) throws java.io.IOException {
		String sLinea = "";
		sLinea = "		<fo:static-content flow-name=\"xsl-region-before\">\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "      <fo:block font-size=\"16pt\" font-weight=\"bold\" padding-top=\"10pt\">\n"
				+ texto + " " + param + "      </fo:block>\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = " 		</fo:static-content>\n";
		tmpFoFileStream.write(sLinea.getBytes());
	} // Fin funcion fncGenerarTitulo

	public void fncGenerarPiePaginaAntes(FileOutputStream tmpFoFileStream)
			throws java.io.IOException {
		String sLinea;
		sLinea = "		<fo:static-content flow-name=\"xsl-region-after\">\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "      <fo:block >\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "       <fo:table table-layout=\"fixed\">\n";
		tmpFoFileStream.write(sLinea.getBytes());
	} // Fin funcion fncGenerarPiePaginaAntes

	public void fncGenerarPiePaginaDespues(FileOutputStream tmpFoFileStream)
	throws java.io.IOException {
		fncGenerarPiePaginaDespues(tmpFoFileStream,m05bConstantesInformes.IDIOMA_C,"Página");
	}
	public void fncGenerarPiePaginaDespues(FileOutputStream tmpFoFileStream,String idioma, String pagina)
			throws java.io.IOException {
		String sLinea;
		sLinea = "	    <fo:table-body font-family=\"Helvetica\" font-size=\"6pt\">\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "	    <fo:table-row>\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "	    <fo:table-cell >\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "      <fo:block text-align=\"left\">"
				+ miComun.getDetFechaActual(idioma)
				+ "</fo:block>";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "	    </fo:table-cell>\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "	    <fo:table-cell >\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "      <fo:block text-align=\"right\">";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = pagina+" <fo:page-number/> \n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "</fo:block>";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "	    </fo:table-cell>\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "	    </fo:table-row>\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "	    </fo:table-body>\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "       </fo:table>\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "      </fo:block>\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = " 		</fo:static-content>\n";
		tmpFoFileStream.write(sLinea.getBytes());
	} // Fin funcion fncGenerarPiePaginaDespues
	public void fncGenerarPiePagina(FileOutputStream tmpFoFileStream, String dir)
	throws java.io.IOException {
		fncGenerarPiePagina(tmpFoFileStream,dir,m05bConstantesInformes.IDIOMA_C,"Página");
	}
	public void fncGenerarPiePagina(FileOutputStream tmpFoFileStream, String dir,String idioma, String pagina)
			throws java.io.IOException {
		String sLinea = "";
		fncGenerarPiePaginaAntes(tmpFoFileStream);
		sLinea = "	    <fo:table-column column-width=\"80mm\"/>\n";
		tmpFoFileStream.write(sLinea.getBytes());
		if (dir.equals(m05bConstantesInformes.DIR_HORIZONTAL))
			sLinea = "	    <fo:table-column column-width=\"160mm\"/>\n";
		else
			sLinea = "	    <fo:table-column column-width=\"80mm\"/>\n";
		tmpFoFileStream.write(sLinea.getBytes());
		fncGenerarPiePaginaDespues(tmpFoFileStream,idioma,pagina);
	} // Fin funcion fncGenerarPiePagina

	public void fncImprimirFinPagina(FileOutputStream tmpFoFileStream)
			throws java.io.IOException {
		String sLinea = "";
		sLinea = "	    </fo:table-body>\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "       </fo:table>\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "      </fo:flow>\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "   </fo:page-sequence>\n";
		tmpFoFileStream.write(sLinea.getBytes());
	} // Fin funcion fncImprimirFinPagina

	/**
	 * renders an FO inputsource into a PDF file which is rendered directly to
	 * the response object's OutputStream
	 */
	public void renderFO(HttpServletResponse response) throws ServletException {
		try {
			miLog.addTraza("", "", "Inicio render FO",
					m05bConstantes.LOG_NIVEL_BAJO);

			FileInputStream file = new FileInputStream(sFoFileDir
					+ tmpFoFile.getName());
			InputSource foFile = new InputSource(file);

			ByteArrayOutputStream out = new ByteArrayOutputStream();

			response.reset();
			OutputStream oOut = response.getOutputStream();
			BufferedOutputStream bOut = new BufferedOutputStream(oOut);
			Driver driver = new Driver(foFile, out);
			  org.apache.avalon.framework.logger.Logger logger = new org.apache.avalon.framework.logger.ConsoleLogger(org.apache.avalon.framework.logger.ConsoleLogger.LEVEL_FATAL);
	            org.apache.fop.messaging.MessageHandler.setScreenLogger(logger);
	            driver.setLogger(logger);
			driver.setRenderer(Driver.RENDER_PDF);
			driver.run();

			response.setContentLength(out.size());
			response.setContentType("application/pdf");

			bOut.write(out.toByteArray());
			out.close();
			bOut.flush();
			bOut.close();
			tmpFoFile.delete();
			response.flushBuffer();
			miLog.addTraza("", "", "Fin render FO",
					m05bConstantes.LOG_NIVEL_BAJO);

		} catch (Exception ex) {
			throw new ServletException(ex);
		}
	} // Fin funcion renderFO

	public void generarPDFdesdeFO(HttpServletResponse response)
			throws FOPException {
		try {
			miLog.addTraza("", "", "Inicio generar PDF desde FO",
					m05bConstantes.LOG_NIVEL_BAJO);

			Driver driver = new Driver();
			  org.apache.avalon.framework.logger.Logger logger = new org.apache.avalon.framework.logger.ConsoleLogger(org.apache.avalon.framework.logger.ConsoleLogger.LEVEL_FATAL);
	            org.apache.fop.messaging.MessageHandler.setScreenLogger(logger);
	            driver.setLogger(logger);
			driver.setRenderer(Driver.RENDER_PDF);
			miLog.addTraza("", "", "   ... Ver si existe el directorio",
					m05bConstantes.LOG_NIVEL_BAJO);

			// Si no existe el directorio lo crea
			File f = new File(sFoFileDir);
			if (!f.exists()) {
				f.mkdir();
			}
			String ficheroFO = sFoFileDir + tmpFoFile.getName();
			miLog.addTraza("", "", "   ... Cargar los datos del FO",
					m05bConstantes.LOG_NIVEL_BAJO);

			// Cargar los datos del .FO
			FileInputStream file = new FileInputStream(ficheroFO);
			BufferedInputStream bfile = new BufferedInputStream(file);
			driver.setInputSource(new InputSource(bfile));
			miLog.addTraza("", "", "   ... Crear el temporal para el pdf",
					m05bConstantes.LOG_NIVEL_BAJO);
			// Crear un temporal que va a ser el .pdf
			String sPdfFileDir = sFoFileDir;
			File pdfFileDir = new File(sPdfFileDir);
			File tmpPdfFile = File.createTempFile("m05b", ".pdf", pdfFileDir);

			FileOutputStream fileout = new FileOutputStream(tmpPdfFile);
			BufferedOutputStream bfileout = new BufferedOutputStream(fileout);
			driver.setOutputStream(bfileout);
			driver.run();

			bfile.close();
			bfileout.close();
			miLog.addTraza("", "", "   ... Longitud el fichero pdf",
					m05bConstantes.LOG_NIVEL_BAJO);

			// Longitud del Fichero PDF.
			Long longitud = new Long(tmpPdfFile.length());
			String sLongitud = "" + longitud;
			int iLongitud = Integer.parseInt(sLongitud);

			response.setContentLength((int) iLongitud);
			response.setContentType("application/pdf");

			byte[] fileBytes = new byte[longitud.intValue()];
			FileInputStream fisficheroPdf = new FileInputStream(tmpPdfFile);
			fisficheroPdf.read(fileBytes);
			ServletOutputStream os = response.getOutputStream();
			((OutputStream) os).write(fileBytes);
			((OutputStream) os).flush();
			((OutputStream) os).close();
			miLog.addTraza("", "", "   ... Borrado del fichero fo",
					m05bConstantes.LOG_NIVEL_BAJO);

			// BORRAR EL FICHERO FO
			File fichero = new File(ficheroFO);
			boolean borrado = fichero.delete();
			boolean borrado2 = tmpPdfFile.delete();
			tmpFoFile.delete();

			miLog.addTraza("", "", "   ... Fin generar PDF desde FO",
					m05bConstantes.LOG_NIVEL_BAJO);

		} catch (Exception e) {
			System.err.println("EXCEPCION !!! : Error pasando de FO a PDF: "
					+ e);
		}
	} // Fin funcion generarPDFdesdeFO

}