package utiliServlet;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
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 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.m05bFileLog;

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


/**
 * Inserte aquí la descripción del tipo.
 * Fecha de creación: (09/12/05)
 */
    
public class m05bRecuperarInfServlet extends javax.servlet.http.HttpServlet
{
	   m05bFileLog miLog = new m05bFileLog();
		java.sql.Connection conn=null;
	    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
   {
      performTask(request, response);
   }

   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 {
	  java.sql.Connection conn=null;
	  PreparedStatement pstmt = null;
	  ResultSet rs = null;
      String tipo="", desde="", hasta="", sql="", persona="";
	  double dNumReg=0.0 ;
	  try {
      	 HttpSession session = request.getSession(true);
      	/* Iker. idioma */
		Locale idiomaLocal = (Locale) session.getAttribute("Local");
		String idiomaSes = ((idiomaLocal.getLanguage() == null) ? "es"
				: idiomaLocal.getLanguage());
	
		String formatoFecha="dd/MM/yyyy";
		
		if (!idiomaSes.equals("es")) {
			
			formatoFecha = "yyyy/MM/dd";
		}
     	 persona = (String) session.getAttribute("persona");	 
      	 m05bFileLog miLog = new m05bFileLog();
		 miLog.addTraza(persona, "Recuperar Inf Servlet", "INICIO", m05bConstantes.LOG_NIVEL_BAJO);
     	       	 
		 m05bComun miComun = new m05bComun();
		 m05bConexion miConex = new m05bConexion();
		 conn = miConex.getConnection();

		 tipo=request.getParameter("Tipo");
		 desde=request.getParameter("Desde");
		 hasta=request.getParameter("Hasta");

		 if ( 	(tipo.equals(m05bConstantes.LST_TAR_SOLICITADAS)) ||
		 	 	(tipo.equals(m05bConstantes.LST_TAR_CANCELADAS))  )  {
				 sql=" 	update " + m05bConstantes.TAB_TARJETAS + 
			 	 			" set " + m05bConstantes.COL_31_IMPRESO + " = 'N' " +
			 	 			//" , " + m05bConstantes.COL_31_FIMPRESION + " = '' " +
							" where " + m05bConstantes.COL_31_MATRICULA + "||" + m05bConstantes.COL_31_TIPO + " IN " +
								" ( select " + m05bConstantes.COL_31_MATRICULA + "||" + m05bConstantes.COL_31_TIPO + 
									" from "+ m05bConstantes.TAB_TARJETAS +
						 	 		" where " + m05bConstantes.COL_31_IMPRESO + " = 'S' " +
						 	 		" and " + m05bConstantes.COL_31_FIMPRESION + 
										" between to_date('" + desde + "','"+formatoFecha+"') and " +
										"to_date('"+ hasta + "','"+formatoFecha+"')";
		 } else if ( 	(tipo.equals(m05bConstantes.LST_SEG_SOLICITADAS)) ||
		 	 	(tipo.equals(m05bConstantes.LST_SEG_CANCELADAS))  )  {
		 	 		sql=" 	update " + m05bConstantes.TAB_HIST_SEGUROS + 
			 	 			" set " + m05bConstantes.COL_13_IMPRESO + " = 'N' " +
			 	 			//" , " + m05bConstantes.COL_13_FIMPRESION + " = '' " +
							" where " + m05bConstantes.COL_13_CODIGO + " IN " +
								" ( select " + m05bConstantes.COL_13_CODIGO + 
								" from " + m05bConstantes.TAB_HIST_SEGUROS + 
								" where " + m05bConstantes.COL_13_IMPRESO + " = 'S' " +
						 	 		" and " + m05bConstantes.COL_13_FIMPRESION + 
										" between to_date('" + desde + "','"+formatoFecha+"') and " +
										"to_date('"+ hasta + "','"+formatoFecha+"')";
 		} else if (tipo.equals(m05bConstantes.LST_ASIG_ACTADEV)) {
			 	sql=" 	update " + m05bConstantes.TAB_ASIGNACION + 
			 	 			" set " + m05bConstantes.COL_01_IMPRESO + " = 'N' " +
			 	 			//" , " + m05bConstantes.COL_01_FIMPRESO + " = '' " +
							" where " + m05bConstantes.COL_01_CODASIG + " IN " +
								" ( SELECT  " + m05bConstantes.COL_01_CODASIG + 
									" from " + m05bConstantes.TAB_ASIGNACION + 
									" where " + m05bConstantes.COL_01_IMPRESO + " = 'S' " +
						 	 		" and " + m05bConstantes.COL_01_FIMPRESO + 
										" between to_date('" + desde + "','"+formatoFecha+"') and " +
										"to_date('"+ hasta + "','"+formatoFecha+"'))";
 		} else if (tipo.equals(m05bConstantes.LST_ASIG_ACTADEC)) {
			 	sql=" 	update " + m05bConstantes.TAB_ASIGNACION + 
			 	 			" set " + m05bConstantes.COL_01_DECRETO + " = 'N' " +
			 	 			//" , " + m05bConstantes.COL_01_FENTREGA + " = '' " +
							" where " + m05bConstantes.COL_01_CODASIG + " IN " +
								" ( SELECT  " + m05bConstantes.COL_01_CODASIG + 
									" from " + m05bConstantes.TAB_ASIGNACION + 
									" where " + m05bConstantes.COL_01_DECRETO + " = 'S' " +
						 	 		" and " + m05bConstantes.COL_01_FDECRETO + 
										" between to_date('" + desde + "','"+formatoFecha+"') and " +
										"to_date('"+ hasta + "','"+formatoFecha+"'))";
	    } else if (tipo.equals(m05bConstantes.LST_TARJ_CAMBIO)) {
			 	sql=" 	update " + m05bConstantes.TAB_TARJETAS + 
			 	 			" set " + m05bConstantes.COL_31_CAMBIO + " = 'N' " +
			 	 			//" , " + m05bConstantes.COL_01_FENTREGA + " = '' " +
							" where " + m05bConstantes.COL_31_TARJETA + " IN " +
								" ( SELECT  " + m05bConstantes.COL_31_TARJETA + 
									" from " + m05bConstantes.TAB_TARJETAS + 
									" where " + m05bConstantes.COL_31_CAMBIO + " = 'S' " +
									" and " + m05bConstantes.COL_31_FCAMBIO + " is not null " +
						 	 		" and " + m05bConstantes.COL_31_FCAMBIO + 
										" between to_date('" + desde + "','"+formatoFecha+"') and " +
										"to_date('"+ hasta + "','"+formatoFecha+"'))";
		}
 		
		if (tipo.equals(m05bConstantes.LST_TAR_SOLICITADAS)) {
			 	sql += " and " + m05bConstantes.COL_31_SITUACION + " = '" +  m05bConstantes.TAR_SOLICITADA + "')";
		} else if (tipo.equals(m05bConstantes.LST_TAR_CANCELADAS)) {
			 	sql += " and " + m05bConstantes.COL_31_SITUACION + " = '" +  m05bConstantes.TAR_CANCELADA + "')";
		} else if (tipo.equals(m05bConstantes.LST_SEG_SOLICITADAS)) {
			 	sql += " and " + m05bConstantes.COL_13_ESTADO + " = '" +  m05bConstantes.SEG_SOLICITADA + "')";
		} else if (tipo.equals(m05bConstantes.LST_SEG_CANCELADAS)) {
			 	sql += " and " + m05bConstantes.COL_13_ESTADO + " = '" +  m05bConstantes.SEG_CANCELADA + "')";
		}
		miLog.addTraza(persona, "Recuperar Inf Servlet", "SQL: " + sql, m05bConstantes.LOG_NIVEL_BAJO);
		pstmt = conn.prepareStatement(sql);
		pstmt.executeQuery();
		 
		response.sendRedirect("m05bRecuperarInfJsp.jsp?Mensaje=" + m05bConstantes.MSG_OK);


      } catch (Exception ex) {
      	try {
			response.sendRedirect("m05bError.jsp");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			miLog.addTraza(e);
		}
      } finally{
	   	    try {
				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);
        }
    }
}