package tarjetasServlet;

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

import javax.naming.Context;
import javax.naming.InitialContext;
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;

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


/**
 * Inserte aquí la descripción del tipo.
 * Fecha de creación: (19/09/05)
 */
    
public class m05bImpCargasCajasServlet extends javax.servlet.http.HttpServlet
{
	    public static final String FO_REQUEST_PARAM = "fo";

		java.sql.Connection conn=null;

		String sLinea;
        File foFileDir ;
        File tmpFoFile ;
		FileOutputStream tmpFoFileStream ;

		String persona="";

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

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

   public void performTask(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws ServletException {
	  PreparedStatement pstmt = null;
	  ResultSet rs = null;
      String sFecha="", sNombre="", sNumReg = "", sPriReg= "", sSentencia;
	  double dNumReg=0.0 ;
	   
      try {  
      	 HttpSession session = request.getSession(true);
      	 
      	  ResourceBundle res =  (ResourceBundle)session.getAttribute("resTit");
       	/*Iker. idioma*/
   		Locale idiomaLocal = (Locale)session.getAttribute("Local");
   		String idiomaSes = ((idiomaLocal.getLanguage()==null)?"es":idiomaLocal.getLanguage());	
   	
           String campoTexto="";
           String formatoFecha="dd/MM/yyyy";
           if(!idiomaSes.equals("es")){
   			campoTexto="E";
   			formatoFecha="yyyy/MM/dd";
           }
   			
      	 persona = (String) session.getAttribute("persona");

		 conn = miConex.getConnection();
		 
		 sSentencia=" SELECT  TO_CHAR(" + m05bConstantes.COL_43_FECHA + ",'"+formatoFecha+" HH24:MI:SS') ," + m05bConstantes.COL_43_NOMBRE + 
						"," + m05bConstantes.COL_43_NUMREG + "," + m05bConstantes.COL_43_PRIMERREG + 
						" FROM "+ m05bConstantes.TAB_CARGAGASTOSTARJETAS +
						" ORDER BY 1 DESC" ;
		 miLog.addTraza(persona, "ImpCargasCajas Servlet", "SQL: " + sSentencia,m05bConstantes.LOG_NIVEL_BAJO);
		 pstmt = conn.prepareStatement(sSentencia);
		 rs = pstmt.executeQuery();

         tmpFoFileStream=miInforme.fncAbrirFicheroTemporal();

         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=\"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=\"2cm\" 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());

		 // 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 = "p. <fo:page-number/>\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("infCargTarj.titulo") + "</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());
		         Context ctx =  new InitialContext(System.getProperties());
      	         // --------------    DETALLE DEL LISTADO    --------------
		           		sLinea= "        <fo:table space-after.optimum=\"12pt\">\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-column column-width=\"20mm\"/>\n";
			            	tmpFoFileStream.write(sLinea.getBytes());
		            		sLinea = "	    <fo:table-column column-width=\"100mm\"/>\n";
			            	tmpFoFileStream.write(sLinea.getBytes());
			            	
		                    /*sLinea = "	    <fo:table-header font-family=\"Helvetica\" font-size=\"7pt\" >\n";
			                tmpFoFileStream.write(sLinea.getBytes());
			                sLinea = "	    </fo:table-header>\n";
			                tmpFoFileStream.write(sLinea.getBytes());*/
			            		
			            		///DETALLE
		            		sLinea = "	    <fo:table-body font-family=\"Helvetica\" font-size=\"8pt\">\n";
			            	tmpFoFileStream.write(sLinea.getBytes());
   		                        sLinea = "	    <fo:table-row >\n";
			            		tmpFoFileStream.write(sLinea.getBytes());
			            			// Fecha 
			            			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\" font-weight=\"bold\">\n "+res.getString("infCargTarj.col1")+" </fo:block>";
				 			            tmpFoFileStream.write(sLinea.getBytes());
			            			sLinea = "	    </fo:table-cell>\n";
			            			tmpFoFileStream.write(sLinea.getBytes());
			            			// Nombre
			            			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\" font-weight=\"bold\">\n "+res.getString("infCargTarj.col2")+" </fo:block>\n";
								        tmpFoFileStream.write(sLinea.getBytes());
			            			sLinea = "	    </fo:table-cell>\n";
			            			tmpFoFileStream.write(sLinea.getBytes());
			            			// Num. Registros
			            			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\" font-weight=\"bold\">\n "+res.getString("infCargTarj.col3")+" </fo:block>\n";
							            tmpFoFileStream.write(sLinea.getBytes());
			            			sLinea = "	    </fo:table-cell>\n";
			            			tmpFoFileStream.write(sLinea.getBytes());
			            			// Primer Registro
			            			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\" font-weight=\"bold\">\n "+res.getString("infCargTarj.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());
			            	
			            	int cont=0;

		   		            while (rs.next()) {
			   		    	    sFecha = rs.getString(1)==null ? "":rs.getString(1);
			   		    	    sNombre = rs.getString(2)==null ? "":rs.getString(2);
		       	    			dNumReg = rs.getDouble(3);
								sNumReg = miComun.formatearDblMilesDec(dNumReg);
		       	    			sPriReg = rs.getString(4)==null ? "":rs.getString(4);
   		                        sLinea = "	    <fo:table-row >\n";
			            		tmpFoFileStream.write(sLinea.getBytes());
			            			// Fecha 
			            			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[" + sFecha + "]]></fo:block>";
				 			            tmpFoFileStream.write(sLinea.getBytes());
			            			sLinea = "	    </fo:table-cell>\n";
			            			tmpFoFileStream.write(sLinea.getBytes());
			            			// Nombre
			            			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=\"left\">\n <![CDATA["+ sNombre +"]]></fo:block>\n";
								        tmpFoFileStream.write(sLinea.getBytes());
			            			sLinea = "	    </fo:table-cell>\n";
			            			tmpFoFileStream.write(sLinea.getBytes());
			            			// Num. Registros
			            			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["+ sNumReg +"]]></fo:block>\n";
							            tmpFoFileStream.write(sLinea.getBytes());
			            			sLinea = "	    </fo:table-cell>\n";
			            			tmpFoFileStream.write(sLinea.getBytes());
			            			// Primer Registro
			            			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=\"left\">\n<![CDATA["+sPriReg +"]]></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 bucle while  
			 	      	    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:flow>\n";
                 tmpFoFileStream.write(sLinea.getBytes());

        /*	sLinea = " 		</fo:static-content>\n"; 
        	tmpFoFileStream.write(sLinea.getBytes());*/
                 
         	 sLinea = "   </fo:page-sequence>\n";
             tmpFoFileStream.write(sLinea.getBytes());
             
         sLinea = "</fo:root>\n";
         tmpFoFileStream.write(sLinea.getBytes());

         tmpFoFileStream.close();
         
		 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 (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);
				}
	  		}
	   }
    }  // Fin funcion performTask

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