package sancionesServlet;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Locale;
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.m05bComun;
import m05bClasses.m05bConexion;
import m05bClasses.m05bConstantes;
import m05bClasses.m05bConstantesInformes;
import m05bClasses.m05bFileLog;
import m05bClasses.m05bInformes;

public class m05bImpSancionesPendientesServlet extends
		javax.servlet.http.HttpServlet {
	java.sql.Connection conn = null;
	String sLinea;
	String sFoFileDir = "/datos/m05b/tmp/";
	File foFileDir;
	File tmpFoFile;
	FileOutputStream tmpFoFileStream;

	m05bComun miComun = new m05bComun();
	m05bFileLog miLog = new m05bFileLog();
	m05bInformes miInforme = new m05bInformes();
	m05bConexion miConex = new m05bConexion();

	String sDpto = "";

	public static final String FO_REQUEST_PARAM = "fo";

	// Logger log = null;

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

	// if(log == null)
	// {
	// Hierarchy hierarchy = Hierarchy.getDefaultHierarchy();
	// log = hierarchy.getLoggerFor("fop");
	// log.setPriority(Priority.WARN);
	// }

	private void fncImprimirComienzoPagina(ResourceBundle res)
			throws java.io.IOException, javax.naming.NamingException {
		sLinea = "<fo:page-sequence master-reference=\"general\">\n";
		tmpFoFileStream.write(sLinea.getBytes());

		// REGION BEFORE
		sLinea = "		<fo:static-content flow-name=\"xsl-region-before\" >\n";
		tmpFoFileStream.write(sLinea.getBytes());
		// -------------- CABECERA DEL LISTADO --------------
		// Cabecera 1
		sLinea = "      <fo:block text-align=\"end\">\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "      </fo:block>\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "      <fo:block font-weight=\"bold\" padding-top=\"10pt\">\n "
				+ res.getString("infListSancPend.titulo") + "</fo:block>\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "      <fo:block font-weight=\"bold\" padding-top=\"10pt\">\n<![CDATA[ "
				+ res.getString("infListSancPend.texto1")
				+ sDpto
				+ "]]></fo:block>\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = " 		</fo:static-content>\n";
		tmpFoFileStream.write(sLinea.getBytes());

		// PIE DE PAGINA
		miInforme.fncGenerarPiePagina(tmpFoFileStream,
				m05bConstantesInformes.DIR_VERTICAL);

		// BODY
		sLinea = "	<fo:flow flow-name=\"xsl-region-body\">\n";
		tmpFoFileStream.write(sLinea.getBytes());
		// -------------- DETALLE DEL LISTADO --------------
		sLinea = "        <fo:table space-after.optimum=\"12pt\">\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "	    <fo:table-column column-width=\"40mm\"/>\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "	    <fo:table-column column-width=\"40mm\"/>\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "	    <fo:table-column column-width=\"40mm\"/>\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "	    <fo:table-column column-width=\"40mm\"/>\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "	    <fo:table-body font-family=\"Helvetica\" >\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "	    <fo:table-row >\n";
		tmpFoFileStream.write(sLinea.getBytes());
		// Matricula
		sLinea = "	    <fo:table-cell padding-top=\"2mm\" border-width=\"0.1mm\" >\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "      <fo:block  font-size=\"10pt\" font-weight=\"bold\"  text-align=\"center\">\n "
				+ res.getString("infListSancPend.col1") + "</fo:block>";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "	    </fo:table-cell>\n";
		tmpFoFileStream.write(sLinea.getBytes());
		// Tipo de Infraccion
		sLinea = "	    <fo:table-cell padding-top=\"2mm\" border-width=\"0.1mm\" >\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "      <fo:block font-size=\"10pt\" font-weight=\"bold\" text-align=\"center\">\n "
				+ res.getString("infListSancPend.col2") + "</fo:block>\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "	    </fo:table-cell>\n";
		tmpFoFileStream.write(sLinea.getBytes());
		// Nº Expediente
		sLinea = "	    <fo:table-cell padding-top=\"2mm\" border-width=\"0.1mm\" >\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "      <fo:block font-size=\"10pt\" font-weight=\"bold\" text-align=\"center\">\n"
				+ res.getString("infListSancPend.col3") + "</fo:block>\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "	    </fo:table-cell>\n";
		tmpFoFileStream.write(sLinea.getBytes());
		// Fecha Notificacion
		sLinea = "	    <fo:table-cell padding-top=\"2mm\" border-width=\"0.1mm\" >\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "      <fo:block font-size=\"10pt\" font-weight=\"bold\" text-align=\"center\">\n"
				+ res.getString("infListSancPend.col4") + "</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-row >\n";
		tmpFoFileStream.write(sLinea.getBytes());

	}

	// Agurtzane Mar12: contador en listados
	private void imprimirTotal(int intCont, boolean bolGeneral,
			ResourceBundle res) throws java.io.IOException,
			javax.naming.NamingException {
		sLinea = "	    <fo:table-row>\n";
		tmpFoFileStream.write(sLinea.getBytes());
		// vacías
		for (int i = 0; i < 3; i++) {
			sLinea = "	    <fo:table-cell>\n<fo:block>\n</fo:block>\n</fo:table-cell>\n";
			tmpFoFileStream.write(sLinea.getBytes());
		}
		// Contador
		sLinea = "	    <fo:table-cell>\n";
		tmpFoFileStream.write(sLinea.getBytes());
		if (bolGeneral)
			sLinea = "      <fo:block font-weight=\"bold\" text-align=\"right\"  padding-top=\"26pt\">\n <![CDATA["
					+ res.getString("infListSancPend.texto2")
					+ intCont
					+ "]]></fo:block>\n";
		else
			sLinea = "      <fo:block font-weight=\"bold\" text-align=\"right\"  padding-top=\"26pt\">\n<![CDATA[ "
					+ res.getString("infListSancPend.texto3")
					+ intCont
					+ "]]></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());
	}

	// Fin Agurtzane Mar12: contador en listados
	public void performTask(javax.servlet.http.HttpServletRequest request,
			javax.servlet.http.HttpServletResponse response)
			throws ServletException {
		PreparedStatement pstmt = null;
		ResultSet rs = null;

		try {
			HttpSession session = request.getSession(true);
			ResourceBundle res = (ResourceBundle) session
					.getAttribute("resTit");

			Locale idiomaLocal = (Locale) session.getAttribute("Local");
			String idiomaSes = ((idiomaLocal.getLanguage() == null) ? "es"
					: idiomaLocal.getLanguage());
			String campoTexto = "", campoTexto2 = "", campoTexto3 = "C";
			String formatoFecha="dd/MM/yyyy";
			if (!idiomaSes.equals("es")) {
				campoTexto = "E";
				campoTexto2 = "E_";
				campoTexto3 = "E";
				formatoFecha = "yyyy/MM/dd";
			}
			conn = miConex.getConnection();

			// Obtención de información de BD
			// Vehículo
			String matricula = "", sMatricula = "", sTipoInfraccion = "", sNExpediente = "", sFNotificacion = "";
			String sDptoAnt = "";

			sDpto = request.getParameter("DPTO");
			if (sDpto == null) {
				sDpto = "";
			}
			String strDpto = sDpto;// Agurtzane Mar12: contador en listados
			// String sSentenciaDPTO = " SELECT " +
			// m05bConstantes.COL_06_DESCDPTO +
			// " FROM " + m05bConstantes.TAB_DEPARTAMENTOS +
			// " WHERE " + m05bConstantes.COL_06_CODDPTO +"='" + sDPTO +"'";

			String sSentencia = "SELECT NVL(" + campoTexto2
					+ m05bConstantes.COL_06_DESCDPTO + ","+ m05bConstantes.COL_06_DESCDPTO + "),"
					+ m05bConstantes.COL_45_MATRICULA + ","
					+ m05bConstantes.COL_45_TIPO + ",NVL("+campoTexto
					+ m05bConstantes.COL_99_DESCRIPCION + ","
					+ m05bConstantes.COL_99_DESCRIPCION + "),"
					+ m05bConstantes.COL_45_NEXP_DENUNCIA + ","
					+ m05bConstantes.COL_45_NEXP_SANCION + ",TO_CHAR("
					+ m05bConstantes.COL_45_FNOTIF_DPTO + ",'" + formatoFecha
					+ "'), DECODE(" + m05bConstantes.COL_45_NEXP_DENUNCIA
					+ ",''," + m05bConstantes.COL_45_NEXP_SANCION + ","
					+ m05bConstantes.COL_45_NEXP_DENUNCIA + ") " + "FROM "
					+ m05bConstantes.TAB_SANCIONES + ","
					+ m05bConstantes.TAB_VEHICULOS + ","
					+ m05bConstantes.TAB_DEPARTAMENTOS + ","
					+ m05bConstantes.TAB_DESCRIPCIONES + " WHERE "
					+ m05bConstantes.COL_45_MATRICULA + "="
					+ m05bConstantes.COL_34_MATRICULA + " AND "
					+ m05bConstantes.COL_34_CODDPTO + "="
					+ m05bConstantes.COL_06_CODDPTO + " AND "
					+ m05bConstantes.COL_45_FREC_DATOS + " Is Null AND "
					+ m05bConstantes.COL_99_CODTABLA + "(+)="
					+ m05bConstantes.DESC_TIPOS_SANCION + " AND "
					+ m05bConstantes.COL_45_TIPO + "= "
					+ m05bConstantes.COL_99_CODDESC + "(+) ";
			if (!(sDpto.equals(""))) {
				sSentencia = sSentencia + " AND "
						+ m05bConstantes.COL_34_CODDPTO + " = " + sDpto;
			}
			sSentencia = sSentencia + " ORDER BY "
					+ m05bConstantes.COL_34_DESDPTO;
			miLog.addTraza(m05bConstantes.LOG_NO_USER,
					m05bConstantes.LOG_NO_SRC, "SQL: " + sSentencia,
					m05bConstantes.LOG_NIVEL_BAJO);

			pstmt = conn.prepareStatement(sSentencia);
			rs = pstmt.executeQuery();

			tmpFoFileStream = miInforme.fncAbrirFicheroTemporal();

			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=\"21cm\" margin-top=\"2cm\" margin-bottom=\"2cm\" margin-left=\"2.5cm\" margin-right=\"2.5cm\">\n";
			tmpFoFileStream.write(sLinea.getBytes());
			sLinea = "		<fo:region-before extent=\"2cm\"/>\n";
			tmpFoFileStream.write(sLinea.getBytes());
			sLinea = "		<fo:region-body  margin-top=\"2.8cm\" margin-bottom=\"1.5cm\" />\n";
			tmpFoFileStream.write(sLinea.getBytes());
			sLinea = "		<fo:region-after  extent=\"1cm\"/>\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());

			int cont = 0;
			// Agurtzane Mar12: contador en listados
			int intCont = 0, intContParcial = 0;
			// Fin Agurtzane Mar12: contador en listados
			while (rs.next()) {
				// Agurtzane Mar12: contador en listados
				intCont++;
				intContParcial++;
				// Fin Agurtzane Mar12: contador en listados
				sDpto = rs.getString(1) == null ? "" : rs.getString(1);
				sMatricula = rs.getString(2) == null ? "" : rs.getString(2);
				sTipoInfraccion = rs.getString(4) == null ? "" : rs
						.getString(4);
				sNExpediente = rs.getString(5) == null ? "" : rs.getString(5);
				sFNotificacion = rs.getString(7) == null ? "" : rs.getString(7);

				if (((!(sDpto.equals(sDptoAnt)))) || (cont == 40)) {
					if (sDptoAnt != "") {
						imprimirTotal(intContParcial, false, res);// Agurtzane
																	// Mar12:
																	// contador
																	// en
																	// listados
						miInforme.fncImprimirFinPagina(tmpFoFileStream);
					}
					fncImprimirComienzoPagina(res);
					cont = 0;
					intContParcial = 0;// Agurtzane Mar12: contador en listados
				} else {
					cont = cont + 1;
					sLinea = "	    <fo:table-row >\n";
					tmpFoFileStream.write(sLinea.getBytes());
				}
				sDptoAnt = sDpto;

				// Matricula
				sLinea = "	    <fo:table-cell padding-top=\"0.2mm\" border-width=\"0.1mm\" border-style=\"solid\">\n";
				tmpFoFileStream.write(sLinea.getBytes());
				sLinea = "      <fo:block  text-align=\"center\">\n <![CDATA["
						+ sMatricula + "]]></fo:block>";
				tmpFoFileStream.write(sLinea.getBytes());
				sLinea = "	    </fo:table-cell>\n";
				tmpFoFileStream.write(sLinea.getBytes());
				// Tipo de Infraccion
				sLinea = "	    <fo:table-cell padding-top=\"0.2mm\" border-width=\"0.1mm\" border-style=\"solid\">\n";
				tmpFoFileStream.write(sLinea.getBytes());
				sLinea = "      <fo:block  text-align=\"center\">\n<![CDATA[ "
						+ sTipoInfraccion + "]]></fo:block>\n";
				tmpFoFileStream.write(sLinea.getBytes());
				sLinea = "	    </fo:table-cell>\n";
				tmpFoFileStream.write(sLinea.getBytes());
				// Nº Expediente
				sLinea = "	    <fo:table-cell padding-top=\"0.2mm\" border-width=\"0.1mm\" border-style=\"solid\">\n";
				tmpFoFileStream.write(sLinea.getBytes());
				sLinea = "      <fo:block  text-align=\"center\">\n<![CDATA["
						+ sNExpediente + "]]></fo:block>\n";
				tmpFoFileStream.write(sLinea.getBytes());
				sLinea = "	    </fo:table-cell>\n";
				tmpFoFileStream.write(sLinea.getBytes());
				// Fecha Notificacion
				sLinea = "	    <fo:table-cell padding-top=\"0.2mm\" border-width=\"0.1mm\" border-style=\"solid\">\n";
				tmpFoFileStream.write(sLinea.getBytes());
				sLinea = "      <fo:block  text-align=\"center\">\n<![CDATA["
						+ sFNotificacion + "]]></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());
			}
			// Agurtzane Mar12: contador en listados
			intContParcial++;
			imprimirTotal(intContParcial, false, res);
			if ((strDpto.equals("")))
				imprimirTotal(intCont, true, res);
			// Fin Agurtzane Mar12: contador en listados
			miInforme.fncImprimirFinPagina(tmpFoFileStream);
			rs.close();

			sLinea = "</fo:root>\n";
			tmpFoFileStream.write(sLinea.getBytes());

			miLog.addTraza(m05bConstantes.LOG_NO_USER,
					m05bConstantes.LOG_NO_SRC, "Antes Generar PDF desde FO",
					m05bConstantes.LOG_NIVEL_BAJO);
			miInforme.generarPDFdesdeFO(response);
			miLog.addTraza(m05bConstantes.LOG_NO_USER,
					m05bConstantes.LOG_NO_SRC, "Despues Generar PDF desde FO",
					m05bConstantes.LOG_NIVEL_BAJO);

			tmpFoFileStream.close();

		} 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();
				if (conn != null)
					conn.close();
			} catch (SQLException e2) {
				try {
					response.sendRedirect("m05bError.jsp");
				} catch (IOException e) {
					// TODO Auto-generated catch block
					miLog.addTraza(e);
				}
			}
		}
	}

}