package asignacionServlet;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
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.m05bDescrip;
import m05bClasses.m05bFileLog;
import m05bClasses.m05bInformes;

public class m05bImpAsigPtesServlet extends javax.servlet.http.HttpServlet
{
		java.sql.Connection conn = null;
		String sLinea;
        File foFileDir;
        File tmpFoFile;
		FileOutputStream tmpFoFileStream;
	    String sTipo="", sDescTipo="", sGrupo="", sFechaHasta="", sDescGrupo="",
	    	   sRango="", sDescRango="", sTitGrupo="", sEstado="";
        String sCodAsig="";

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

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

   private void fncImprimirComienzoPagina(ResourceBundle res)throws java.io.IOException, javax.naming.NamingException
   {
	   // PAGE-SEQUENCE DEL LISTADO
	   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());

	   if (sEstado.equals("PE")) {
		   sLinea = "      <fo:block font-weight=\"bold\" padding-top=\"5pt\">\n " + res.getString("infPendientesAsig.titulo1")+ miComun.getFechaActual() + "</fo:block>\n";
	   } else if (sEstado.equals("PD")) {
		   sLinea = "      <fo:block font-weight=\"bold\" padding-top=\"5pt\">\n " + res.getString("infPendientesAsig.titulo2") + miComun.getFechaActual() + "</fo:block>\n";
	   } else {
		   sLinea = "      <fo:block font-weight=\"bold\" padding-top=\"5pt\">\n " + res.getString("infPendientesAsig.titulo3") + miComun.getFechaActual() + "</fo:block>\n";
	   }

	   tmpFoFileStream.write(sLinea.getBytes());
	   sLinea = "      <fo:block font-weight=\"bold\" padding-top=\"5pt\" font-size=\"9pt\">\n <![CDATA[" + res.getString("infPendientesAsig.col1") + sDescTipo + "]]></fo:block>\n";
	   tmpFoFileStream.write(sLinea.getBytes());
	   sLinea = "      <fo:block font-weight=\"bold\" padding-top=\"2pt\" font-size=\"9pt\">\n <![CDATA[" + res.getString("infPendientesAsig.col2") + sTitGrupo + "]]></fo:block>\n";
	   tmpFoFileStream.write(sLinea.getBytes());
	   sLinea = "      <fo:block font-weight=\"bold\" padding-top=\"2pt\" font-size=\"9pt\">\n <![CDATA[" + res.getString("infPendientesAsig.col3") + sDescRango + "]]></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=\"20mm\"/>\n";
			            	tmpFoFileStream.write(sLinea.getBytes());
		            		sLinea = "	    <fo:table-column column-width=\"20mm\"/>\n";
			            	tmpFoFileStream.write(sLinea.getBytes());
		            		sLinea = "	    <fo:table-column column-width=\"70mm\"/>\n";
			            	tmpFoFileStream.write(sLinea.getBytes());
		            		sLinea = "	    <fo:table-column column-width=\"30mm\"/>\n";
			            	tmpFoFileStream.write(sLinea.getBytes());
		            		sLinea = "	    <fo:table-column column-width=\"30mm\"/>\n";
			            	tmpFoFileStream.write(sLinea.getBytes());
			            	sLinea = "	    <fo:table-body font-family=\"Helvetica\" font-size=\"8pt\">\n";
			            	tmpFoFileStream.write(sLinea.getBytes());
   		                        sLinea = "	    <fo:table-row >\n";
			            		tmpFoFileStream.write(sLinea.getBytes());
			            			// Solicitud 
			               			sLinea = "	    <fo:table-cell border-width=\"0.1mm\" >\n";
			            			tmpFoFileStream.write(sLinea.getBytes());
							            sLinea = "      <fo:block font-weight=\"bold\" text-align=\"center\">\n " + res.getString("infPendientesAsig.col4") +"</fo:block>";
			 			            tmpFoFileStream.write(sLinea.getBytes());
			            			sLinea = "	    </fo:table-cell>\n";
			            			tmpFoFileStream.write(sLinea.getBytes());
			            			// Matrícula
			            			sLinea = "	    <fo:table-cell border-width=\"0.1mm\">\n";
			            			tmpFoFileStream.write(sLinea.getBytes());
							            sLinea = "      <fo:block font-weight=\"bold\" text-align=\"center\">\n " + res.getString("infPendientesAsig.col5") +"</fo:block>\n";
							            tmpFoFileStream.write(sLinea.getBytes());
			            			sLinea = "	    </fo:table-cell>\n";
			            			tmpFoFileStream.write(sLinea.getBytes());
			            			// Nombre
			            			sLinea = "	    <fo:table-cell border-width=\"0.1mm\">\n";
			            			tmpFoFileStream.write(sLinea.getBytes());
							            sLinea = "      <fo:block font-weight=\"bold\" text-align=\"center\">\n " + res.getString("infPendientesAsig.col6") +"</fo:block>\n";
							            tmpFoFileStream.write(sLinea.getBytes());
			            			sLinea = "	    </fo:table-cell>\n";
			            			tmpFoFileStream.write(sLinea.getBytes());
			            			// F. Desde
			            			sLinea = "	    <fo:table-cell border-width=\"0.1mm\" >\n";
			            			tmpFoFileStream.write(sLinea.getBytes());
							            sLinea = "      <fo:block font-weight=\"bold\" text-align=\"center\">\n" + res.getString("infPendientesAsig.col7") +"</fo:block>\n";
							            tmpFoFileStream.write(sLinea.getBytes());
			            			sLinea = "	    </fo:table-cell>\n";
			            			tmpFoFileStream.write(sLinea.getBytes());
			            			// F. Hasta
			            			sLinea = "	    <fo:table-cell border-width=\"0.1mm\" >\n";
			            			tmpFoFileStream.write(sLinea.getBytes());
							            sLinea = "      <fo:block font-weight=\"bold\" text-align=\"center\">\n" + res.getString("infPendientesAsig.col8") +"</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 funcion fncImprimirComienzoPagina

   public void performTask(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws ServletException
   {
	  java.sql.Connection conn=null;
	  PreparedStatement pstmt = null;
	  ResultSet rs = null;
	   
      try {  
      		HttpSession session = request.getSession(true);
      		String persona = (String) session.getAttribute("persona");


         	 
    		ResourceBundle res =  (ResourceBundle)session.getAttribute("resTit");
    		
    		Locale idiomaLocal = (Locale)session.getAttribute("Local");
    		String idiomaSes = ((idiomaLocal.getLanguage()==null)?"es":idiomaLocal.getLanguage());	
    		String formatoFecha="dd/mm/yyyy hh24:mi:ss";
    		String campoTexto="";
    		String idioma=m05bConstantesInformes.IDIOMA_C;
    		if(!idiomaSes.equals("es")){
    			formatoFecha="yyyy/mm/dd hh24:mi:ss";
    			campoTexto="E";
    			idioma=m05bConstantesInformes.IDIOMA_E;
    		}
    		
      	 // Obtención de parametros
      		sEstado = request.getParameter("Estado")==null?"":request.getParameter("Estado").toUpperCase();
            sTipo=request.getParameter("Tipo");
	        if ( (sTipo==null) || (sTipo.equals("")) || (sTipo.equals("N")) )  {
	        	if(idiomaSes.equals("es"))
				sDescTipo="NO PERMANENTE";
	        	else
	        		sDescTipo="EZ BEHIN-BETIKOA";
			} else if (sTipo.equals("S")) {
				if(idiomaSes.equals("es"))
				sDescTipo="PERMANENTE";
				else
					sDescTipo="BEHIN-BETIKOA";
			} else if (sTipo.equals("T")) {
				if(idiomaSes.equals("es"))
				sDescTipo="TODAS";
				else
					sDescTipo="GUZTIAK";
			}
            sGrupo=request.getParameter("Grupo");
            if (sGrupo.equals("")) {
            	sGrupo="***";
            }
            miLog.addTraza(persona, "Imp Asig Ptes Servlet", "GRUPO: " + sGrupo, m05bConstantes.LOG_NIVEL_BAJO);
            sDescGrupo=request.getParameter("DescGrupo")==null?"":request.getParameter("DescGrupo");
			if (!sGrupo.equals("***"))  {
					      	sDescGrupo=miComun.ListaCaracteres(sDescGrupo);
							sTitGrupo=miDescrip.getNombreGrupo(sGrupo,idioma);
			}
            miLog.addTraza(persona, "Imp Asig Ptes Servlet", "TIT GRUPO: " + sTitGrupo, m05bConstantes.LOG_NIVEL_BAJO);
            sRango = request.getParameter("Rango");
			sDescRango = miDescrip.getDescripcion(m05bConstantes.DESC_RANGOS, sRango,idioma);
            miLog.addTraza(m05bConstantes.LOG_NO_USER, m05bConstantes.LOG_NO_SRC, " DESC GRUPO: " + sDescGrupo, m05bConstantes.LOG_NIVEL_BAJO);
			
         String sNombre="", sFechaHasta = "", sFechaDesde = "", sMatricula="";
		 String sql = "select "+m05bConstantes.COL_01_CODASIG+","+m05bConstantes.COL_01_MATRICULA+
		 	 				","+ m05bConstantes.COL_21_NOMBRE+",TO_CHAR("+m05bConstantes.COL_01_FDESDE+",'"+formatoFecha+"')"+
							",TO_CHAR("+m05bConstantes.COL_01_FHASTA+",'"+formatoFecha+"'),"+m05bConstantes.COL_21_NOMBRE+
						" from "+ m05bConstantes.TAB_ASIGNACION+","+m05bConstantes.TAB_PERSONAL +
						" where "+m05bConstantes.COL_01_FINALIZA+"='N'"+
						" and "+m05bConstantes.COL_21_DNI+" = "+m05bConstantes.COL_01_DNI ;
		 
		 if (!(sTipo.equals("T")))  {
				sql = sql + " and "+m05bConstantes.COL_01_ASIG+"  = '" + sTipo + "'";
		 }
		 if (!(sFechaHasta.equals(""))){
				sql = sql + " and "+m05bConstantes.COL_01_ORDEN+" = '" + sFechaHasta + "'";
		 }
		 if ( !sGrupo.equals("***") ) {
		        sql = sql + " and "+m05bConstantes.COL_01_ORDEN+" IN ("  + sDescGrupo + ")";
		 } 
		 if ( !sRango.equals("") ) {
		        sql = sql + " and "+m05bConstantes.COL_01_ORDEN+" = '"  + sRango + "'";
		 } 
		 if (sEstado.equals("PE")) {
			 sql = sql + " and " + m05bConstantes.COL_01_ENTREGA + " = 'N'";
		 } else if (sEstado.equals("PD")) {
			 sql = sql + " and " + m05bConstantes.COL_01_ENTREGA + " = 'S'"
			 		   + " and " + m05bConstantes.COL_01_FINALIZA + " = 'N'";
		 }

		 miLog.addTraza(m05bConstantes.LOG_NO_USER, m05bConstantes.LOG_NO_SRC, "SQL: " + sql, m05bConstantes.LOG_NIVEL_BAJO);
		 conn = miConex.getConnection();
		 pstmt = conn.prepareStatement(sql);
		 rs = pstmt.executeQuery();
			 
         tmpFoFileStream=miInforme.fncAbrirFicheroTemporal();
		 miLog.addTraza(m05bConstantes.LOG_NO_USER, m05bConstantes.LOG_NO_SRC, "Fichero Temporal Abierto" , m05bConstantes.LOG_NIVEL_BAJO);
		 
         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 
         miInforme.fncGenerarLayout(tmpFoFileStream, m05bConstantesInformes.DIR_VERTICAL, m05bConstantesInformes.NUM_LINEAS_2);
		 miLog.addTraza(m05bConstantes.LOG_NO_USER,m05bConstantes.LOG_NO_SRC,"Despues layout", m05bConstantes.LOG_NIVEL_BAJO);
		 	 
			           	int cont=0;
						fncImprimirComienzoPagina(res);
		   		        while (rs.next()) {
		   		    	    sCodAsig=rs.getString(1)==null ? "":rs.getString(1);
	       	    			sMatricula = rs.getString(2)==null ? "":rs.getString(2);
	       	    			sNombre = rs.getString(3)==null ? "":rs.getString(3);
	       	    			sFechaDesde= rs.getString(4)==null ? "":rs.getString(4);
	       	    			sFechaHasta= rs.getString(5)==null ? "":rs.getString(5);
	       	    			   if (cont==50){
			                          miInforme.fncImprimirFinPagina(tmpFoFileStream);
	       	    			    	  fncImprimirComienzoPagina(res);
	       	    			          cont=0;
	       	    			   	} else{
			       	    			  ++cont;
			            	    } 
		   		                      sLinea = "	    <fo:table-row >\n";
					            	  tmpFoFileStream.write(sLinea.getBytes());
			            			// Asignacion
			            			sLinea = "	    <fo:table-cell border-width=\"0.1mm\" border-style=\"solid\">\n";
			            			tmpFoFileStream.write(sLinea.getBytes());
							            sLinea = "      <fo:block  text-align=\"center\">\n " + sCodAsig +"</fo:block>";
							            tmpFoFileStream.write(sLinea.getBytes());
			            			sLinea = "	    </fo:table-cell>\n";
			            			tmpFoFileStream.write(sLinea.getBytes());
			            			// Matricula
			            			sLinea = "	    <fo:table-cell border-width=\"0.1mm\" border-style=\"solid\">\n";
			            			tmpFoFileStream.write(sLinea.getBytes());
							            sLinea = "      <fo:block  text-align=\"center\">\n <![CDATA["+ sMatricula +"]]></fo:block>\n";
							            tmpFoFileStream.write(sLinea.getBytes());
			            			sLinea = "	    </fo:table-cell>\n";
			            			tmpFoFileStream.write(sLinea.getBytes());
			            			// Nombre
			            			sLinea = "	    <fo:table-cell border-width=\"0.1mm\" border-style=\"solid\">\n";
			            			tmpFoFileStream.write(sLinea.getBytes());
							            sLinea = "      <fo:block  text-align=\"left\">\n<![CDATA["+sNombre+"]]></fo:block>\n";
							            tmpFoFileStream.write(sLinea.getBytes());
			            			sLinea = "	    </fo:table-cell>\n";
			            			tmpFoFileStream.write(sLinea.getBytes());
			            			// F.Desde
			            			sLinea = "	    <fo:table-cell border-width=\"0.1mm\" border-style=\"solid\">\n";
			            			tmpFoFileStream.write(sLinea.getBytes());
							            sLinea = "      <fo:block  text-align=\"center\">\n<![CDATA["+sFechaDesde+"]]></fo:block>\n";
							            tmpFoFileStream.write(sLinea.getBytes());
			            			sLinea = "	    </fo:table-cell>\n";
			            			tmpFoFileStream.write(sLinea.getBytes());
			            			// F. Hasta
			            			sLinea = "	    <fo:table-cell border-width=\"0.1mm\" border-style=\"solid\">\n";
			            			tmpFoFileStream.write(sLinea.getBytes());
							            sLinea = "      <fo:block  text-align=\"center\">\n<![CDATA["+sFechaHasta+"]]></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());
			        }
			    miLog.addTraza(m05bConstantes.LOG_NO_USER, m05bConstantes.LOG_NO_SRC, "Va a imprimir fin pagina" , m05bConstantes.LOG_NIVEL_BAJO);
			    miInforme.fncImprimirFinPagina(tmpFoFileStream);
			    miLog.addTraza(m05bConstantes.LOG_NO_USER, m05bConstantes.LOG_NO_SRC, "Fin pagina OK" , m05bConstantes.LOG_NIVEL_BAJO);
			    
         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);
         
      } catch (Exception ex) {
      	try {
			response.sendRedirect("m05bError.jsp");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			miLog.addTraza(e);
		}
      } finally{
	   	    try {
				if (tmpFoFileStream != null)
			        tmpFoFileStream.close();
	   	    	
				if (rs != null)
					rs.close();
				if (pstmt != null)
					pstmt.close();
				if (conn != null)
					conn.close();
			} catch (Exception e2) {
				try {
					response.sendRedirect("m05bError.jsp");
				} catch (IOException e) {
					// TODO Auto-generated catch block
					miLog.addTraza(e);
				}
	  		}
	   }
    }
}