package rentingServlet;

import java.io.IOException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Locale;

import javax.servlet.http.HttpSession;

import m05bClasses.m05bComun;
import m05bClasses.m05bConexion;
import m05bClasses.m05bConstantes;
import m05bClasses.m05bFileLog;
import m05bClasses.m05bGenerarClave;


/**
 * Inserte aquí la descripción del tipo.
 * Fecha de creación: (29/08/05)
 */
public class m05bCargarRentingServlet extends javax.servlet.http.HttpServlet {m05bFileLog miLog = new m05bFileLog();
/**
 * Process incoming HTTP POST requests
 *
 * @param request Object that encapsulates the request to the servlet
 * @param response Object that encapsulates the response from the servlet
 */    

	java.sql.Connection conn=null;

public void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, java.io.IOException {

	performTask(request, response);

}
/**
 * Returns the servlet info string.
 */
public String getServletInfo() {

	return super.getServletInfo();

}
/**
 * Initializes the servlet.
 */
public void init() {
	// insert code to initialize the servlet here
		
}



/**
 * Process incoming requests for information
 *
 * @param request Object that encapsulates the request to the servlet
 * @param response Object that encapsulates the response from the servlet
 */
public void performTask(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) {

	   m05bFileLog miLog = new m05bFileLog();
       String sql="", sqlInsert="", FHasta, matricula="", matricAnt="", precio="", fecha="";
	   PreparedStatement pstmt = null, pstmtInsert = null;
	   ResultSet rs = null;
	   int codigo=0;
       
       try  {
	   	   
			// Conexion
			try {
					m05bConexion miConex = new m05bConexion();
					conn = miConex.getConnection();
					conn.setAutoCommit(false);  // Al final si todo ha ido bien se hace commit
	   		} catch (Exception SQLException) {
	   			miLog.addTraza(SQLException);	
	   			try {
		  			conn.rollback();  // Ha habido problemas, se deshacen todos los cambios
		  		} catch (SQLException e2){
		  			throw new Exception(e2);
		  		}
			} 
		    try{
		    	m05bComun miComun = new m05bComun();
		        FHasta = request.getParameter("FHasta");
		    	HttpSession session = request.getSession(true);
				/* Iker. idioma */
				Locale idiomaLocal = (Locale) session.getAttribute("Local");
				String idiomaSes = ((idiomaLocal.getLanguage() == null) ? "es"
						: idiomaLocal.getLanguage());
				if (idiomaSes.equals("es")) 
					FHasta = FHasta.substring(6,10) + FHasta.substring(3,5) + "01";
				else
					FHasta = FHasta.substring(0,4) + FHasta.substring(5,7) + "01";
		        
			//	System.out.println("m05b - Cargar Renting Servlet: FECHA HASTA: " + FHasta);
		        
   				m05bGenerarClave miCodigo = new m05bGenerarClave();
				String aux="to_number(" + m05bConstantes.COL_41_CODIGO + ")";
   				codigo = miCodigo.getNextId(m05bConstantes.TAB_CUOTAS,aux);
		        
		   	   // Seleccionar los vehículos a tratar
		   	   	sql = "select " + m05bConstantes.COL_34_MATRICULA + ", TO_CHAR(" + m05bConstantes.COL_34_FMATRIC + ",'YYYYMMDD')" +
						", " + m05bConstantes.COL_34_PRECIO +", TO_CHAR(" + m05bConstantes.COL_41_FECHA + ",'YYYYMMDD') " + 
						" from " + m05bConstantes.TAB_VEHICULOS  + ", " + m05bConstantes.TAB_CUOTAS  +
				    	" where " +  m05bConstantes.COL_41_MATRICULA + "(+) = " + m05bConstantes.COL_34_MATRICULA +
				    	" and " +  m05bConstantes.COL_34_REGADQUIS + " = '" + m05bConstantes.VEH_REG_RENTING + "' " +
				    	" and " +  m05bConstantes.COL_34_FMATRIC + " < TO_DATE('" + FHasta + "','YYYYMMDD') " +
				    	" and (" +  m05bConstantes.COL_34_SITUACION + " = '" + m05bConstantes.VEH_ALTA + "'" +
				    	" or (" +  m05bConstantes.COL_34_SITUACION + " = '" + m05bConstantes.VEH_BAJA + "'" +
				    	" and " +  m05bConstantes.COL_34_FBAJA + " >= TO_DATE('" + FHasta + "','YYYYMMDD') ))" +
				    	" and " + m05bConstantes.COL_34_MATRICULA + " not in (select " + m05bConstantes.COL_41_MATRICULA + " from " + m05bConstantes.TAB_CUOTAS + " where " + m05bConstantes.COL_41_FECHA + "=TO_DATE('"+ FHasta + "','YYYYMMDD')) " +
						" order by " +  m05bConstantes.COL_34_MATRICULA + ", " + m05bConstantes.COL_41_FECHA + " DESC";
		        //System.out.println("m05b - Cargar Cuotas Renting: SQL: " + sql );
            	pstmt = conn.prepareStatement(sql);
	        	rs = pstmt.executeQuery();
		       	//pstmt = conn.createStatement();
		   		//pstmt.execute(sql);
		   		//rs = pstmt.getResultSet();
		   		while (rs.next()) {
			   			matricula=rs.getString(1);
			   			if (!(matricula.equals(matricAnt))) {
				   				precio=rs.getString(3);
				   				fecha=rs.getString(4)==null?rs.getString(2):rs.getString(4);
				   				//Carga de la tabla de Cuotas de Renting
				   				while (Integer.parseInt(fecha) < Integer.parseInt(FHasta)) {
					   					// Se inserta un registro por mes
					   				fecha = miComun.addMesFechaCorta(fecha, 1);
									fecha = fecha.substring(6,10) + fecha.substring(3,5) + fecha.substring(0,2);
									sqlInsert="insert into	 "  + m05bConstantes.TAB_CUOTAS +
												" (" + m05bConstantes.COL_41_CODIGO + "," + m05bConstantes.COL_41_MATRICULA +
												"," + m05bConstantes.COL_41_IMPORTE + "," + m05bConstantes.COL_41_FECHA + ") " +
												" values " +
												"( " + codigo + ", '" + matricula + "', " + precio + 
												", TO_DATE('" + fecha + "','YYYYMMDD') )";
					       			//System.out.println("m05b - Cargar Cuotas Renting: INSERT: " + sqlInsert );
					            	pstmtInsert = conn.prepareStatement(sqlInsert);
					   				pstmtInsert.execute();
					   				++codigo;
					   			}  // Fin while
			   			}  // Fin if
			   			matricAnt=matricula;
		   	   	}  // Fin while
				//Si todo ha ido bien se actualizan los cambios en la BD
				    conn.commit();
					response.sendRedirect("m05bCuotasRentingJsp.jsp?Mensaje=" + m05bConstantes.MSG_OK );
			} catch (Exception SQLException) {
				miLog.addTraza(SQLException);	
				try {
		  			conn.rollback();  // Ha habido problemas, se deshacen todos los cambios
		  		} catch (SQLException e2){
		  			throw new Exception(e2);
		  		}
			} 	finally{
					if (rs != null)
						rs.close();
					if (pstmtInsert != null)
						pstmtInsert.close();
					if (pstmt != null)
						pstmt.close();
					if (conn != null)
						conn.close();
			}  
	} catch(Throwable theException)	{
		// uncomment the following line when unexpected exceptions
		// are occuring to aid in debugging the problem.
		miLog.addTraza(theException);
		try {
			response.sendRedirect("m05bError.jsp");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			miLog.addTraza(e);
		}
	}  // Fin try 
}  // Fin funcion performTask
} // Fin clase m05bCargarRentingServlet