package rentingServlet;

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

import javax.servlet.http.HttpSession;

import m05bBD.m05bRenting;
import m05bClasses.m05bComun;
import m05bClasses.m05bConexion;
import m05bClasses.m05bConstantes;
import m05bClasses.m05bFileLog;

/**
 * Inserte aquí la descripción del tipo.
 * Fecha de creación: (26/07/04)
 */

public class m05bGrabarRentingServlet 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
 */
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) {

       String sCodigo, sFecha, sMatricula, sImporte, accion;
   	   java.sql.Connection conn=null;
	   PreparedStatement pstmt = null;
	   ResultSet rs = null;
       String sql="";
	   
       try

	{
        HttpSession session = request.getSession(true);
     	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";
         }
        m05bComun miComun = new m05bComun();
        m05bComun comun = new m05bComun();
		m05bRenting renting = (m05bRenting)session.getAttribute("m05bRenting");
		sCodigo = request.getParameter("Codigo");
		renting.setRen_codigo(sCodigo);
		sFecha=request.getParameter("Fecha");
        if (sFecha==null)	       
	    	sFecha="";
		renting.setRen_fecha(sFecha);
        sMatricula=request.getParameter("Matricula");
        renting.setRen_matricula(sMatricula);
        sImporte=request.getParameter("Importe");
        if (sImporte==null || sImporte.equals("NULL") || sImporte.equals(""))
        	sImporte="0";
        sImporte=miComun.ImportesABasedatos(sImporte);
        renting.setRen_importe(sImporte);
		accion=request.getParameter("Accion");
		try{
			m05bConexion miConex = new m05bConexion();
			conn = miConex.getConnection();
			if (accion.equals(m05bConstantes.ACC_ACTUALIZAR))  {
                sql = "SELECT TO_CHAR(" +m05bConstantes.COL_41_FECHA + ",'"+formatoFecha+"') FROM  " + m05bConstantes.TAB_CUOTAS +
                      " WHERE " + m05bConstantes.COL_41_MATRICULA +"='" + sMatricula+"' AND TO_CHAR(" +m05bConstantes.COL_41_FECHA + ",'"+formatoFecha+"')='"+ sFecha +"' AND " +
                               m05bConstantes.COL_41_CODIGO +" != '"+sCodigo+"'";				
		              //System.out.println("m05b - Grabar Cambio rango SQL transferencias: " + sql );
		              pstmt = conn.prepareStatement(sql);
		              rs = pstmt.executeQuery();
		              if (rs.next()){  
		                  rs.getString(1);
                          response.sendRedirect("m05bCuotasJsp.jsp?Matricula="+sMatricula+ "&Mensaje=Existe");}
                      else {
        			       sql = "update " +m05bConstantes.TAB_CUOTAS+
                           " set "+m05bConstantes.COL_41_IMPORTE+" =  "+ sImporte+
                           " , "+m05bConstantes.COL_41_FECHA+" =  TO_DATE('"+sFecha+"','"+formatoFecha+"')" +
                           " where	"+m05bConstantes.COL_41_CODIGO+" = "+sCodigo;
	                       pstmt = conn.prepareStatement(sql);
			               pstmt.executeUpdate();
                           conn.commit();
				           if (pstmt != null)
				           	pstmt.close();                                   	
						   response.sendRedirect("m05bCuotasJsp.jsp?Matricula="+sMatricula);
			}}
			else if (accion.equals(m05bConstantes.ACC_INSERTAR))  {

                sql = "SELECT TO_CHAR(" +m05bConstantes.COL_41_FECHA + ",'"+formatoFecha+"') FROM  " + m05bConstantes.TAB_CUOTAS +
                      " WHERE " + m05bConstantes.COL_41_MATRICULA +"='" + sMatricula+"' AND TO_CHAR(" +m05bConstantes.COL_41_FECHA + ",'"+formatoFecha+"')='"+ sFecha +"' order by " + m05bConstantes.COL_41_CODIGO +" desc";
		              //System.out.println("m05b - Grabar Cambio rango SQL transferencias: " + sql );
		              pstmt = conn.prepareStatement(sql);
		              rs = pstmt.executeQuery();
		              if (rs.next()){  
		                  rs.getString(1);
                          response.sendRedirect("m05bCuotasJsp.jsp?Matricula="+sMatricula+ "&Mensaje=Existe");}
                      else{
        				sql="insert into	 " +m05bConstantes.TAB_CUOTAS+
						"("+m05bConstantes.COL_41_CODIGO+","+m05bConstantes.COL_41_MATRICULA+","+m05bConstantes.COL_41_IMPORTE+
	                     ","+m05bConstantes.COL_41_FECHA+ ") " +
						" values ('"+sCodigo+"','"+sMatricula+"',"+sImporte+
					    ",TO_DATE('"+sFecha+"','"+formatoFecha+"'))";
        	            pstmt = conn.prepareStatement(sql);
					    pstmt.executeUpdate();
				    	 conn.commit();
	     				if (pstmt != null)
	 	    				pstmt.close();                        	
	     				response.sendRedirect("m05bCuotasJsp.jsp?Matricula="+sMatricula);                     	

			}}
			else   {
				sql=   "delete from  " +m05bConstantes.TAB_CUOTAS+
                " where "+m05bConstantes.COL_41_CODIGO+" = " + sCodigo;
                pstmt = conn.prepareStatement(sql);
		        pstmt.executeUpdate();
	    	    conn.commit();
				if (pstmt != null)
					pstmt.close();
				response.sendRedirect("m05bCuotasJsp.jsp?Matricula="+sMatricula);
			}
		} 	catch (Exception SQLException) {
				miLog.addTraza(SQLException);
				response.sendRedirect("m05bError.jsp");
		} 	finally{
				if (rs != null)
					rs.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);
		}
	}
}
}
