package transferenciasServlet;

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

import javax.servlet.http.HttpSession;

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

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

public class m05bGrabarTransferenciasServlet 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;
       	String sMatricula;
       	String sFdesde;
       	String sFhasta;
       	String sRango;
       	String sImporte;
       	String sImporteAnt;
       	String accion;
       	double dImporte =0.0;
       	double dImporteAnt =0.0;
       	double dDiferencia=0.0;
		java.sql.Connection conn=null;
		PreparedStatement pstmt = null;
        m05bComun miComun = new m05bComun();
		String sql="";
	    ResultSet rs = null;
       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 comun = new m05bComun();
		m05bTransferencias transfe = (m05bTransferencias)session.getAttribute("m05bTransferencias");
        sCodigo=request.getParameter("Codigo");
        transfe.setTra_codigo(sCodigo);
		sMatricula = request.getParameter("Matricula");
		transfe.setTra_matricula(sMatricula);
		sFdesde=request.getParameter("fdesde");
		transfe.setTra_fdesde(sFdesde);
        sFhasta=request.getParameter("fhasta");
		transfe.setTra_fdesde(sFhasta);
        sRango=request.getParameter("Rango");
        transfe.setTra_rango(sRango);
        sImporte=request.getParameter("Importe");
        if (sImporte==null || sImporte.equals("NULL") || sImporte.equals(""))
        	sImporte="0";        
        sImporte=miComun.ImportesABasedatos(sImporte);     
        sImporteAnt=request.getParameter("ImporteAnt");
        if (sImporteAnt==null || sImporteAnt.equals("NULL") || sImporteAnt.equals(""))
        	sImporteAnt="0";        
        sImporteAnt=miComun.ImportesABasedatos(sImporteAnt);        
        transfe.setTra_importe(sImporte);
		accion=request.getParameter("Accion");
        m05bConexion miConex = new m05bConexion();
			conn = miConex.getConnection();

		try{

			if (accion.equals(m05bConstantes.ACC_ACTUALIZAR))  {
              sql = "SELECT TO_CHAR(" +m05bConstantes.COL_40_FHASTA + ",'"+formatoFecha+"'),"+m05bConstantes.COL_40_IMPORTE +" FROM  " + m05bConstantes.TAB_TRANSFERENCIAS +
                    " WHERE " + m05bConstantes.COL_40_MATRICULA +"='" + sMatricula+"' AND TO_CHAR(" +m05bConstantes.COL_40_FHASTA + ",'"+formatoFecha+"')= '"+sFhasta+"' AND "+
                    " TO_CHAR(" +m05bConstantes.COL_40_FDESDE + ",'"+formatoFecha+"')='"+ sFdesde +"' AND " +
                               m05bConstantes.COL_40_CODIGO +" != '"+sCodigo+"'";								

		            pstmt = conn.prepareStatement(sql);
		            rs = pstmt.executeQuery();
		            if (rs.next()){  
                       response.sendRedirect("m05bTransferenJsp.jsp?Matricula="+sMatricula+ "&Mensaje=Existe");}
				    else {
      			       sql = "update " +m05bConstantes.TAB_TRANSFERENCIAS+
                       " set "+m05bConstantes.COL_40_RANGO+" = '" +sRango+
                       "' , "+m05bConstantes.COL_40_IMPORTE+" =  "+ sImporte+
                       " , "+m05bConstantes.COL_40_FHASTA+" =  TO_DATE('"+sFhasta+"','"+formatoFecha+"')" +
                       " , "+m05bConstantes.COL_40_FDESDE+" =  TO_DATE('"+sFdesde+"','"+formatoFecha+"')" +
				       " where	"+m05bConstantes.COL_40_CODIGO+" = "+sCodigo;
	                pstmt = conn.prepareStatement(sql);
			        pstmt.executeUpdate();
					  dImporte = Double.valueOf(sImporte).doubleValue();
					  dImporteAnt = Double.valueOf(sImporteAnt).doubleValue();
					  dDiferencia= dImporte-dImporteAnt;
					  if (dDiferencia != 0.0){
	 			       sql = "update " +m05bConstantes.TAB_AMORTIZACION+
                       " set "+m05bConstantes.COL_39_IMPORTE+" = " + m05bConstantes.COL_39_IMPORTE + " + (" + dDiferencia +
                       ") , "+m05bConstantes.COL_39_AMORTIZA+" =  "+ m05bConstantes.COL_39_AMORTIZA + " + (" + dDiferencia +
				       ") where	"+m05bConstantes.COL_39_MATRICULA+" = '"+sMatricula + "' AND "+m05bConstantes.COL_39_FECHA+" in (SELECT MAX("+
				       m05bConstantes.COL_39_FECHA+ ") FROM "+ m05bConstantes.TAB_AMORTIZACION +  " where	"+m05bConstantes.COL_39_MATRICULA+" = '"+sMatricula + "')";
		                pstmt = conn.prepareStatement(sql);
				        pstmt.executeUpdate();
				       }
		    	    conn.commit();
				    if (pstmt != null)
   				    pstmt.close();                	   					    	
				    response.sendRedirect("m05bTransferenJsp.jsp?Matricula="+sMatricula);
			}}
			else if (accion.equals(m05bConstantes.ACC_INSERTAR))  {

              sql = "SELECT TO_CHAR(" +m05bConstantes.COL_40_FHASTA + ",'"+formatoFecha+"') FROM  " + m05bConstantes.TAB_TRANSFERENCIAS +
                    " WHERE " + m05bConstantes.COL_40_MATRICULA +"='" + sMatricula+"' AND TO_CHAR(" +m05bConstantes.COL_40_FHASTA + ",'"+formatoFecha+"')= '"+sFhasta+"' AND "+
                    " TO_CHAR(" +m05bConstantes.COL_40_FDESDE + ",'"+formatoFecha+"')= '"+sFdesde+"'  order by " + m05bConstantes.COL_40_CODIGO +" desc";
		            pstmt = conn.prepareStatement(sql);
		            rs = pstmt.executeQuery();
		            if (rs.next()){  
                       response.sendRedirect("m05bTransferenJsp.jsp?Matricula="+sMatricula+ "&Mensaje=Existe");}
                    else {
        				sql="insert into	 " +m05bConstantes.TAB_TRANSFERENCIAS+
						"("+m05bConstantes.COL_40_RANGO+","+m05bConstantes.COL_40_MATRICULA+","+m05bConstantes.COL_40_IMPORTE+
	                     ","+m05bConstantes.COL_40_FDESDE+","+m05bConstantes.COL_40_FHASTA+","+m05bConstantes.COL_40_CODIGO+
	                     ") " +
						" values ('"+sRango+"','"+sMatricula+"',"+sImporte+
					    ",TO_DATE('"+sFdesde+"','"+formatoFecha+"')"+
					    ",TO_DATE('"+sFhasta+"','"+formatoFecha+"'),"+sCodigo+")";
        	            pstmt = conn.prepareStatement(sql);
					    pstmt.executeUpdate();
				    	 conn.commit();
	     				if (pstmt != null)
	 	    				pstmt.close();                      	
	     	 			response.sendRedirect("m05bTransferenJsp.jsp?Matricula="+sMatricula);
			}}
			else   {
				sql=   "delete from  " +m05bConstantes.TAB_TRANSFERENCIAS+
                " where "+m05bConstantes.COL_40_CODIGO+" = " + sCodigo;
                pstmt = conn.prepareStatement(sql);
		        pstmt.executeUpdate();
	    	    conn.commit();
				if (pstmt != null)
 				pstmt.close();
				response.sendRedirect("m05bTransferenJsp.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);
		}
	}
}
}

