package ordentrabajoServlet;

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 m05bImpOrdPtesServlet extends javax.servlet.http.HttpServlet
{
		java.sql.Connection conn=null;
		String sLinea;
        File foFileDir ;
        File tmpFoFile ;
		FileOutputStream tmpFoFileStream ;
	    String sOrder="";
        
	    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,String idioma)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());
                    sLinea = "      <fo:block font-weight=\"bold\" padding-top=\"5pt\">\n " + res.getString("infOrdPenFe.titulo")+ miComun.getFechaActual(idioma) + "</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,idioma,res.getString("pagina")); 
		    
            //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=\"10mm\"/>\n";
			            	tmpFoFileStream.write(sLinea.getBytes());
		            		sLinea = "	    <fo:table-column column-width=\"17mm\"/>\n";
			            	tmpFoFileStream.write(sLinea.getBytes());
		            		sLinea = "	    <fo:table-column column-width=\"25mm\"/>\n";
			            	tmpFoFileStream.write(sLinea.getBytes());
		            		sLinea = "	    <fo:table-column column-width=\"18mm\"/>\n";
			            	tmpFoFileStream.write(sLinea.getBytes());
		            		sLinea = "	    <fo:table-column column-width=\"50mm\"/>\n";
			            	tmpFoFileStream.write(sLinea.getBytes());
		            		sLinea = "	    <fo:table-column column-width=\"50mm\"/>\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());
			            			// Orden 
			               			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("infOrdPenFe.col1")+"</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("infOrdPenFe.col2")+"</fo:block>\n";
							            tmpFoFileStream.write(sLinea.getBytes());
			            			sLinea = "	    </fo:table-cell>\n";
			            			tmpFoFileStream.write(sLinea.getBytes());
			            			// F. Entrada
			            			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("infOrdPenFe.col3")+"</fo:block>\n";
							            tmpFoFileStream.write(sLinea.getBytes());
			            			sLinea = "	    </fo:table-cell>\n";
			            			tmpFoFileStream.write(sLinea.getBytes());
			            			// Km. Entrada
			            			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("infOrdPenFe.col4")+"</fo:block>\n";
							            tmpFoFileStream.write(sLinea.getBytes());
			            			sLinea = "	    </fo:table-cell>\n";
			            			tmpFoFileStream.write(sLinea.getBytes());
			            			// Taller
			            			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("infOrdPenFe.col5")+"</fo:block>\n";
							            tmpFoFileStream.write(sLinea.getBytes());
			            			sLinea = "	    </fo:table-cell>\n";
			            			tmpFoFileStream.write(sLinea.getBytes());
			            			// Reparaciones
			            			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("infOrdPenFe.col6")+"</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);
      		m05bConexion miConex = new m05bConexion();
			conn = miConex.getConnection();
		
			/*Iker. idioma*/
			Locale idiomaLocal = (Locale)session.getAttribute("Local");
	
			ResourceBundle res =  (ResourceBundle)session.getAttribute("resTit");
			String idiomaSes = ((idiomaLocal.getLanguage()==null)?"es":idiomaLocal.getLanguage());	
			String campoTexto="C";
			String formatoFecha="dd/MM/yyyy";
			if(!idiomaSes.equals("es")){
				campoTexto="E";
				formatoFecha="yyyy/MM/dd";
				
			}
      		String persona = (String) session.getAttribute("persona");
      
      	 // Obtención de parametros
            sOrder=request.getParameter("Orden");
	        if ( (sOrder==null) || (sOrder.equals("")) )  {
				sOrder="MATRICULA";
			} 
         String sCodigo="", sMatricula = "", sFechaEntrada = "", sKmsEntrada="",sTaller="",sReparaciones="";
		 String sql="";
		 	 
		 	sql = "select " + m05bConstantes.COL_20_CODIGO + "," + m05bConstantes.COL_20_MATRICULA +
		    			",TO_CHAR(" + m05bConstantes.COL_20_FENTRADA +",'"+formatoFecha+" hh24:mi')," + m05bConstantes.COL_20_DESCRIP +
		    			"," + m05bConstantes.COL_30_DESCRIP + "," + m05bConstantes.COL_20_KM_ENTRADA +
		    	" FROM " + m05bConstantes.TAB_ORDENESTRAB + " , " + m05bConstantes.TAB_TALLER + 
		    	" WHERE " + m05bConstantes.COL_30_CODIGO + " = " + m05bConstantes.COL_20_CODTALLER +
		    			" AND " + m05bConstantes.COL_20_FSALIDA + " IS  NULL" ;

			if (sOrder.equals("MATRICULA"))
				sql += " order by "+ m05bConstantes.COL_20_MATRICULA+","+m05bConstantes.COL_20_FENTRADA+" desc,"+ m05bConstantes.COL_30_DESCRIP;
			else if (sOrder.equals("FECHA"))
				sql += " order by "+ m05bConstantes.COL_20_FENTRADA+" desc,"+m05bConstantes.COL_20_MATRICULA+","+ m05bConstantes.COL_30_DESCRIP;
			else if (sOrder.equals("TALLER"))
				sql += " order by "+  m05bConstantes.COL_30_DESCRIP+","+m05bConstantes.COL_20_MATRICULA+","+m05bConstantes.COL_20_FENTRADA+" desc";
		 
		 
		 miLog.addTraza(persona, "Imp Ot Pendientes Servlet", "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,campoTexto);
						String dNumeroS="";
						while (rs.next()) {
		   		    	    sCodigo=rs.getString(1)==null ? "":rs.getString(1);
	       	    			sMatricula = rs.getString(2)==null ? "":rs.getString(2);
	       	    			sFechaEntrada = rs.getString(3)==null ? "":rs.getString(3);
	       	    			dNumeroS = (rs.getString(6)==null)?"0":rs.getString(6);
	       	    			sKmsEntrada = miComun.formatearDblMiles(new Double(dNumeroS).doubleValue());
	       	    			sKmsEntrada = sKmsEntrada.replaceAll(",","."); 
	       	    			sTaller= rs.getString(5)==null ? "":rs.getString(5);
	       	    			sReparaciones= rs.getString(4)==null ? "":rs.getString(4);
	       	    			   if (cont==50){
			                          miInforme.fncImprimirFinPagina(tmpFoFileStream);
	       	    			    	  fncImprimirComienzoPagina(res,campoTexto);
	       	    			          cont=0;
	       	    			   	} else{
			       	    			  ++cont;
			            	    } 
		   		                      sLinea = "	    <fo:table-row >\n";
					            	  tmpFoFileStream.write(sLinea.getBytes());
			            			// Codigo
			            			sLinea = "	    <fo:table-cell border-width=\"0.1mm\" border-style=\"solid\">\n";
			            			tmpFoFileStream.write(sLinea.getBytes());
							            sLinea = "      <fo:block  text-align=\"center\">\n <![CDATA[" + sCodigo +"]]></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());
			            			// Fecha Entrada
			            			sLinea = "	    <fo:table-cell border-width=\"0.1mm\" border-style=\"solid\">\n";
			            			tmpFoFileStream.write(sLinea.getBytes());
							            sLinea = "      <fo:block  text-align=\"left\">\n<![CDATA["+sFechaEntrada+"]]></fo:block>\n";
							            tmpFoFileStream.write(sLinea.getBytes());
			            			sLinea = "	    </fo:table-cell>\n";
			            			tmpFoFileStream.write(sLinea.getBytes());
			            			// KmsEntrada
			            			sLinea = "	    <fo:table-cell border-width=\"0.1mm\" border-style=\"solid\">\n";
			            			tmpFoFileStream.write(sLinea.getBytes());
							            sLinea = "      <fo:block  text-align=\"center\">\n<![CDATA["+sKmsEntrada+"]]></fo:block>\n";
							            tmpFoFileStream.write(sLinea.getBytes());
			            			sLinea = "	    </fo:table-cell>\n";
			            			tmpFoFileStream.write(sLinea.getBytes());
			            			// Taller
			            			sLinea = "	    <fo:table-cell border-width=\"0.1mm\" border-style=\"solid\">\n";
			            			tmpFoFileStream.write(sLinea.getBytes());
							            sLinea = "      <fo:block  text-align=\"left\">\n<![CDATA["+sTaller+"]]></fo:block>\n";
			            			tmpFoFileStream.write(sLinea.getBytes());
			            			sLinea = "	    </fo:table-cell>\n";
			            			tmpFoFileStream.write(sLinea.getBytes());
	            			        // Reparaciones
			            			sLinea = "	    <fo:table-cell border-width=\"0.1mm\" border-style=\"solid\">\n";
			            			tmpFoFileStream.write(sLinea.getBytes());
							            sLinea = "      <fo:block  text-align=\"left\">\n<![CDATA["+sReparaciones+"]]></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 e3) {
				try {
					response.sendRedirect("m05bError.jsp");
				} catch (IOException e) {
					// TODO Auto-generated catch block
					miLog.addTraza(e);
				}
	  		}
	   }
    }

}