package departamentoServlet;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ResourceBundle;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import m05bClasses.m05bConexion;
import m05bClasses.m05bFileLog;

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

public class m05bImprimirDepartamentoServlet extends
		javax.servlet.http.HttpServlet {
	m05bFileLog miLog = new m05bFileLog();
	java.sql.Connection conn = null;

	public static final String FO_REQUEST_PARAM = "fo";

	public void doPost(javax.servlet.http.HttpServletRequest request,
			javax.servlet.http.HttpServletResponse response)
			throws javax.servlet.ServletException, java.io.IOException {
		try {
			doGet(request, response);
		} catch (Exception e) {
			miLog.addTraza(e);
		}
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException {
		performTask(request, response);
	}

	/**
	 * Initializes the servlet.
	 */
	public void init() {
		// insert code to initialize the servlet here

		// Conexion
		try {
			m05bConexion miConex = new m05bConexion();
			conn = miConex.getConnection();
			conn.setAutoCommit(false); // Al final si todo ha ido bien se hace
										// commit
		} catch (Exception SQLException) {
			try {
				conn.rollback(); // Ha habido problemas, se deshacen todos
									// los cambios
			} catch (SQLException e2) {
				System.err.println("Exception: OutletMaintenanceS.service: "
						+ e2);
			}
			miLog.addTraza(SQLException);
		}
	}

	public void performTask(javax.servlet.http.HttpServletRequest request,
			javax.servlet.http.HttpServletResponse response)
			throws ServletException {
		java.sql.Statement pstmt = null;
		ResultSet rs = null;

		try {
			// Obtención de información de BD
			// Avisos
			// String tabla= request.getParameter("Tabla");

			// String sSqlTablas= " FROM " + m05bConstantes.TAB_DESCRIPCIONES;
			// String sSqlCampos= " SELECT " + m05bConstantes.COL_99_CODDESC + "
			// ," + m05bConstantes.COL_99_DESCRIPCION;
			// String sSqlWhere=" WHERE " + m05bConstantes.COL_99_CODTABLA + " =
			// " + tabla;
			String sSentencia = "select COD_DPTO_06, DESCRIP_06, E_DESCRIP_06, NVL(COD_XLNET_06, ' ') as COD_XLNET_06, NVL(SIT_06, 'B') as SIT_06 from M0506T00";
			   HttpSession session = request.getSession(true); 
			ResourceBundle res =  (ResourceBundle)session.getAttribute("resTit");
			String colcoddesc = "";
			String coldescrip = "";
			String coledesc = "";
			String colcodxlnet = "";
			String colsit = "";

			pstmt = conn.createStatement();
			pstmt.execute(sSentencia);
			rs = pstmt.getResultSet();

			// String foParam = request.getParameter(FO_REQUEST_PARAM);
			String sFoFileDir = "/datos/m05b/tmp/";
			File foFileDir = new File(sFoFileDir);
			File tmpFoFile = File.createTempFile("m05b", "Fo", foFileDir);

			FileOutputStream tmpFoFileStream = new FileOutputStream(tmpFoFile);

			String sLinea;

			sLinea = "<?xml version=\"1.0\" encoding=\"windows-1252\"?>\n";
			tmpFoFileStream.write(sLinea.getBytes());

			sLinea = "<fo:root xmlns:fo=\"http://www.w3.org/1999/XSL/Format\">\n";
			tmpFoFileStream.write(sLinea.getBytes());
			// LAYOUT DEL LISTADO
			sLinea = "<fo:layout-master-set>\n";
			tmpFoFileStream.write(sLinea.getBytes());
			sLinea = "<fo:simple-page-master  master-name=\"general\" page-height=\"29.5cm\" page-width=\"21.5cm\" margin-top=\"0cm\" margin-bottom=\"3cm\" margin-left=\"2cm\" margin-right=\"1cm\">\n";
			tmpFoFileStream.write(sLinea.getBytes());
			sLinea = "		<fo:region-before extent=\"7cm\"/>\n";
			tmpFoFileStream.write(sLinea.getBytes());
			sLinea = "		<fo:region-body margin-bottom=\"1cm\" margin-top=\"3cm\"/>\n";
			tmpFoFileStream.write(sLinea.getBytes());
			sLinea = "		<fo:region-after extent=\"0.5cm\"/>\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());
			// ------------------------------------------------------------------------------------------------------------------------
			sLinea = "<fo:page-sequence master-reference=\"general\">\n";
			tmpFoFileStream.write(sLinea.getBytes());
			// CABECERA
			sLinea = "		<fo:static-content flow-name=\"xsl-region-before\">\n";
			tmpFoFileStream.write(sLinea.getBytes());
			// sLinea = " <fo:block position=\"absolute\" top=\"0cm\"
			// left=\"2.4cm\" width=\"12cm\" height=\"1.7cm\">\n";
			sLinea = "		<fo:block-container position=\"absolute\" top=\"0cm\" left=\"2.4cm\" width=\"12cm\" height=\"1.7cm\">\n";
			tmpFoFileStream.write(sLinea.getBytes());
			// Escudo
			sLinea = "			<fo:external-graphic src=\""
					+ "/datos/m05b/file/images/fop/cabeceraHacFin.jpg\" height=\"1.7cm\" width=\"12cm\"/>\n";
			tmpFoFileStream.write(sLinea.getBytes());
			// sLinea = " </fo:block>\n";
			sLinea = "      </fo:block-container>\n";
			tmpFoFileStream.write(sLinea.getBytes());
			sLinea = "		<fo:block-container position=\"absolute\" top=\"2.5cm\" left=\"2.4cm\" width=\"12cm\" height=\"1.7cm\">\n";
			tmpFoFileStream.write(sLinea.getBytes());
			// Titulo
			sLinea = "      <fo:block font-weight=\"bold\" padding-top=\"10pt\" text-align=\"center\"  >\n "
					+ res.getString("infDepartamentos.titulo") + "</fo:block>\n";
			tmpFoFileStream.write(sLinea.getBytes());
			// sLinea = " </fo:block>\n";
			sLinea = "      </fo:block-container>\n";
			tmpFoFileStream.write(sLinea.getBytes());

			sLinea = "      <fo:block-container position=\"absolute\" top=\"2.5cm\" left=\"2.4cm\" width=\"15cm\" height=\"2.75cm\">\n";
			tmpFoFileStream.write(sLinea.getBytes());
			// Detalle-1
			sLinea = "       <fo:table>\n";
			tmpFoFileStream.write(sLinea.getBytes());
			sLinea = "	    <fo:table-column column-width=\"178mm\"/>\n";
			tmpFoFileStream.write(sLinea.getBytes());
			sLinea = "	    <fo:table-body font-family=\"Helvetica\" font-size=\"10pt\">\n";
			tmpFoFileStream.write(sLinea.getBytes());
			sLinea = "	    <fo:table-row>\n";
			tmpFoFileStream.write(sLinea.getBytes());
			// Blanco1
			sLinea = "	    <fo:table-cell>\n";
			tmpFoFileStream.write(sLinea.getBytes());
			// Departamento
			sLinea = "			<fo:block text-align=\"left\"  font-family=\"Helvetica\" font-weight=\"bold\" font-size=\"8pt\"   >\n ";
			tmpFoFileStream.write(sLinea.getBytes());
			sLinea = "	    	</fo:block>\n";
			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-container>\n";
			tmpFoFileStream.write(sLinea.getBytes());

			sLinea = " 		</fo:static-content>\n";
			tmpFoFileStream.write(sLinea.getBytes());
			// PIE
			sLinea = "		<fo:static-content flow-name=\"xsl-region-after\">\n";
			tmpFoFileStream.write(sLinea.getBytes());
			sLinea = "                 <fo:block line-height=\"14pt\" font-size= \"8pt\" text-align=\"end\">"+res.getString("pagina")+" <fo:page-number/></fo:block>\n";
			tmpFoFileStream.write(sLinea.getBytes());
			sLinea = " 		</fo:static-content>\n";
			tmpFoFileStream.write(sLinea.getBytes());
			// ------------------------------------------------------------------------------------------------------------------------------

			// PAGE-SEQUENCE DEL LISTADO
			// bbsLinea = "<fo:page-sequence master-reference=\"general\">\n";
			// bbtmpFoFileStream.write(sLinea.getBytes());
			sLinea = "	<fo:flow flow-name=\"xsl-region-body\">\n";
			tmpFoFileStream.write(sLinea.getBytes());

			// -------------- CABECERA DEL LISTADO --------------
			// Cabecera 1
			// bb sLinea = " <fo:block-container position=\"absolute\"
			// top=\"0cm\" left=\"3.4cm\" width=\"12cm\" height=\"1.7cm\">\n";
			// bb tmpFoFileStream.write(sLinea.getBytes());
			// bb // Escudo
			// bb sLinea = " <fo:external-graphic src=\"" + urlprin +
			// "/parquemovil/images/fop/cabeceraHacFin.jpg\" height=\"1.7cm\"
			// width=\"12cm\"/>\n";
			// bb tmpFoFileStream.write(sLinea.getBytes());
			// bb sLinea = " </fo:block-container>\n";
			// bb tmpFoFileStream.write(sLinea.getBytes());
			// -------------- LISTADO --------------
			// Definicion de la tabla de descripcions.
			sLinea = "       <fo:table>\n";
			tmpFoFileStream.write(sLinea.getBytes());
			sLinea = "	    <fo:table-column column-width=\"15mm\"/>\n";
			tmpFoFileStream.write(sLinea.getBytes());
			sLinea = "	    <fo:table-column column-width=\"70mm\"/>\n";
			tmpFoFileStream.write(sLinea.getBytes());
			sLinea = "	    <fo:table-column column-width=\"70mm\"/>\n";
			tmpFoFileStream.write(sLinea.getBytes());
			sLinea = "	    <fo:table-column column-width=\"20mm\"/>\n";
			tmpFoFileStream.write(sLinea.getBytes());
			sLinea = "	    <fo:table-column column-width=\"10mm\"/>\n";
			tmpFoFileStream.write(sLinea.getBytes());

			// TABLE HEADER
			sLinea = "	    <fo:table-header font-family=\"Helvetica\" font-size=\"10pt\" position=\"relative\" top=\"14cm\" left=\"4.4cm\" width=\"12cm\" height=\"1.7cm\">\n";
			tmpFoFileStream.write(sLinea.getBytes());
			sLinea = "	    <fo:table-row>\n";
			tmpFoFileStream.write(sLinea.getBytes());
			// Blanco1
			sLinea = "	    <fo:table-cell>\n";
			tmpFoFileStream.write(sLinea.getBytes());
			sLinea = "      <fo:block font-weight=\"bold\" padding-top=\"20pt\" text-align=\"left\"  >\n "
					+ res.getString("infDepartamentos.col1")  + "</fo:block>\n";
			tmpFoFileStream.write(sLinea.getBytes());
			sLinea = "      <fo:block font-weight=\"bold\" padding-top=\"0pt\" text-align=\"left\"  >\n "
					+ "----------" + "</fo:block>\n";
			tmpFoFileStream.write(sLinea.getBytes());
			sLinea = "	    </fo:table-cell>\n";
			tmpFoFileStream.write(sLinea.getBytes());
			// Blanco1
			sLinea = "	    <fo:table-cell>\n";
			tmpFoFileStream.write(sLinea.getBytes());
			sLinea = "      <fo:block font-weight=\"bold\" padding-top=\"20pt\" text-align=\"left\"  >\n "
					+ res.getString("infDepartamentos.col2") + "</fo:block>\n";
			tmpFoFileStream.write(sLinea.getBytes());
			sLinea = "      <fo:block font-weight=\"bold\" padding-top=\"0pt\" text-align=\"left\"  >\n "
					+ "-----------------" + "</fo:block>\n";
			tmpFoFileStream.write(sLinea.getBytes());
			sLinea = "	    </fo:table-cell>\n";
			tmpFoFileStream.write(sLinea.getBytes());
			// Blanco1
			sLinea = "	    <fo:table-cell>\n";
			tmpFoFileStream.write(sLinea.getBytes());
			sLinea = "      <fo:block font-weight=\"bold\" padding-top=\"20pt\" text-align=\"left\"  >\n "
					+ res.getString("infDepartamentos.col3") + "</fo:block>\n";
			tmpFoFileStream.write(sLinea.getBytes());
			sLinea = "      <fo:block font-weight=\"bold\" padding-top=\"0pt\" text-align=\"left\"  >\n "
					+ "--------------------" + "</fo:block>\n";
			tmpFoFileStream.write(sLinea.getBytes());
			sLinea = "	    </fo:table-cell>\n";
			tmpFoFileStream.write(sLinea.getBytes());
			// Blanco1
			sLinea = "	    <fo:table-cell>\n";
			tmpFoFileStream.write(sLinea.getBytes());
			sLinea = "      <fo:block font-weight=\"bold\" padding-top=\"20pt\" text-align=\"left\"  >\n "
					+ res.getString("infDepartamentos.col4") + "</fo:block>\n";
			tmpFoFileStream.write(sLinea.getBytes());
			sLinea = "      <fo:block font-weight=\"bold\" padding-top=\"0pt\" text-align=\"left\"  >\n "
					+ "--------------" + "</fo:block>\n";
			tmpFoFileStream.write(sLinea.getBytes());
			sLinea = "	    </fo:table-cell>\n";
			tmpFoFileStream.write(sLinea.getBytes());
			// Blanco1
			sLinea = "	    <fo:table-cell>\n";
			tmpFoFileStream.write(sLinea.getBytes());
			sLinea = "      <fo:block font-weight=\"bold\" padding-top=\"20pt\" text-align=\"left\"  >\n "
					+ res.getString("infDepartamentos.col5") + "</fo:block>\n";
			tmpFoFileStream.write(sLinea.getBytes());
			sLinea = "      <fo:block font-weight=\"bold\" padding-top=\"0pt\" text-align=\"left\"  >\n "
					+ "-----" + "</fo:block>\n";
			tmpFoFileStream.write(sLinea.getBytes());
			sLinea = "	    </fo:table-cell>\n";
			tmpFoFileStream.write(sLinea.getBytes());
			// Blanco2
			sLinea = "	    <fo:table-cell>\n";
			tmpFoFileStream.write(sLinea.getBytes());
			sLinea = "      <fo:block border-width=\"0.05mm\" border-style=\"solid\" > </fo:block>\n";
			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-header>\n";
			tmpFoFileStream.write(sLinea.getBytes());

			sLinea = "	    <fo:table-body font-family=\"Helvetica\" font-size=\"10pt\" position=\"relative\" top=\"14cm\" left=\"4.4cm\" width=\"12cm\" height=\"1.7cm\">\n";
			tmpFoFileStream.write(sLinea.getBytes());

			while (rs.next()) {
				colcoddesc = rs.getString(1) == null ? "" : rs.getString(1);
				coldescrip = rs.getString(2) == null ? "" : rs.getString(2);
				coledesc = rs.getString(3) == null ? "" : rs.getString(3);
				colcodxlnet = rs.getString(4) == null ? "" : rs.getString(4);
				colsit = rs.getString(5) == null ? "" : rs.getString(5);

				sLinea = "	    <fo:table-row>\n";
				tmpFoFileStream.write(sLinea.getBytes());
				// Blanco1
				sLinea = "	    <fo:table-cell>\n";
				tmpFoFileStream.write(sLinea.getBytes());
				sLinea = "      <fo:block  padding-top=\"4pt\" text-align=\"left\"  >\n <![CDATA["
						+ colcoddesc + "]]></fo:block>\n";
				tmpFoFileStream.write(sLinea.getBytes());
				sLinea = "	    </fo:table-cell>\n";
				tmpFoFileStream.write(sLinea.getBytes());
				// Blanco2
				sLinea = "	    <fo:table-cell>\n";
				tmpFoFileStream.write(sLinea.getBytes());
				sLinea = "      <fo:block text-align=\"left\"  padding-top=\"4pt\">\n <![CDATA["
						+ coldescrip + "]]></fo:block>\n";
				tmpFoFileStream.write(sLinea.getBytes());
				sLinea = "	    </fo:table-cell>\n";
				tmpFoFileStream.write(sLinea.getBytes());
				// Blanco3
				sLinea = "	    <fo:table-cell>\n";
				tmpFoFileStream.write(sLinea.getBytes());
				sLinea = "      <fo:block text-align=\"left\"  padding-top=\"4pt\">\n <![CDATA["
						+ coledesc + "]]></fo:block>\n";
				tmpFoFileStream.write(sLinea.getBytes());
				sLinea = "	    </fo:table-cell>\n";
				tmpFoFileStream.write(sLinea.getBytes());
				// Blanco4
				sLinea = "	    <fo:table-cell>\n";
				tmpFoFileStream.write(sLinea.getBytes());
				sLinea = "      <fo:block text-align=\"right\"  padding-top=\"4pt\">\n <![CDATA["
						+ colcodxlnet + "]]></fo:block>\n";
				tmpFoFileStream.write(sLinea.getBytes());
				sLinea = "	    </fo:table-cell>\n";
				tmpFoFileStream.write(sLinea.getBytes());
				// Blanco5
				sLinea = "	    <fo:table-cell>\n";
				tmpFoFileStream.write(sLinea.getBytes());
				sLinea = "      <fo:block text-align=\"center\"  padding-top=\"4pt\">\n <![CDATA["
						+ colsit + "]]></fo:block>\n";
				tmpFoFileStream.write(sLinea.getBytes());
				sLinea = "	    </fo:table-cell>\n";
				tmpFoFileStream.write(sLinea.getBytes());

				sLinea = "	    </fo:table-row>\n";
				tmpFoFileStream.write(sLinea.getBytes());
			}
			rs.close();

			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());
			sLinea = "</fo:root>\n";
			tmpFoFileStream.write(sLinea.getBytes());
			tmpFoFileStream.close();

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

			renderFO(new InputSource(file), response);

			tmpFoFile.delete();

			response.flushBuffer();

		} catch (Exception ex) {
			try {
				response.sendRedirect("m05bError.jsp");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				miLog.addTraza(e);
			}
		} finally {
			try {
				if (rs != null)
					rs.close();
				if (pstmt != null)
					pstmt.close();
			} catch (SQLException e2) {
				try {
					response.sendRedirect("m05bError.jsp");
				} catch (IOException e) {
					// TODO Auto-generated catch block
					miLog.addTraza(e);
				}
			}
		}
	}

	/**
	 * renders an FO inputsource into a PDF file which is rendered directly to
	 * the response object's OutputStream
	 */
	public void renderFO(InputSource foFile, HttpServletResponse response)
			throws ServletException {
		try {
			ByteArrayOutputStream out = new ByteArrayOutputStream();

			response.reset();
			OutputStream oOut = response.getOutputStream();
			BufferedOutputStream bOut = new BufferedOutputStream(oOut);
			Driver driver = new Driver(foFile, out);
			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();

			// response.flushBuffer();
		} catch (Exception ex) {
			throw new ServletException(ex);
		}
	}
}