package tiposreformaServlet;

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.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.m05bCamposInformes;
import m05bClasses.m05bConexion;
import m05bClasses.m05bFileLog;

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


public class m05bImprimirTiposReformaServlet extends javax.servlet.http.HttpServlet
{
		java.sql.Connection conn=null;
		   m05bFileLog miLog = new m05bFileLog();
   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);
//        }

/**
 * Initializes the servlet.
 */
   public void performTask(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws ServletException
   {
	   java.sql.Statement pstmt = null;
	   ResultSet rs = null;
	   java.sql.Connection conn=null;
	   
	   
      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="";
          if(!idiomaSes.equals("es"))
  			campoTexto="E";
    	  // Obtención de información de BD
      	 	 // `Tipos Reforma
         m05bConexion miConex = new m05bConexion();
		 conn = miConex.getConnection();
		 conn.setAutoCommit(false);  // Al final si todo ha ido bien se hace commit
      
         String sSentencia = "select COD_TIPREF_38, NVL("+campoTexto+"DESC_38,DESC_38) from M0538T00";
         //System.out.println(sSentencia);
         
         
         String colcoddesc ="";
	     String	coldescrip ="";
	     
		       	pstmt = conn.createStatement();
		   		pstmt.execute(sSentencia);
		   		rs = pstmt.getResultSet();
		 
      	 m05bCamposInformes miVehiculo = new m05bCamposInformes();

      
         //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("infTiposReforma.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());
		         Context ctx =  new InitialContext(System.getProperties());


		         // --------------    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=\"55mm\"/>\n";
			        tmpFoFileStream.write(sLinea.getBytes());
		            sLinea = "	    <fo:table-column column-width=\"155mm\"/>\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("infTiposReforma.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("infTiposReforma.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());
			            			//  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);

		            		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());
			            		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();
				if (conn != null)
					conn.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);
        }
    }
}
