package vehiculosServlet;

import java.io.IOException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;

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: (19/05/04)
 */

public class m05bGrabarVehVariosServlet 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 sExpte, sFecha, sMatricula, sCV, sInf1, sInf2;
       String sNotas, sRotulado, sAutorAparc, sNumBast, sKmRevis, sMesRevis;
       String sColor="", fGarantia="", sNSerie="";
	   int id=0;
       
       
	   SimpleDateFormat formatterDate = new SimpleDateFormat ("dd/MM/yyyy");
	   m05bGenerarClave miID = new m05bGenerarClave();
	   
	   java.sql.Connection conn=null;
	   PreparedStatement pstmt = null;
	   ResultSet rs = null;
	   String sql = "";
       String accion=m05bConstantes.ACC_ACTUALIZAR;
	   m05bComun miComun = new m05bComun();
       try

	{

		
        HttpSession session = request.getSession(true);
        m05bComun comun = new m05bComun();
        
		sFecha = request.getParameter("FecGarantia");
        if (sFecha!=null)
	        sFecha=comun.FechaBD(sFecha,"00:00");
        sMatricula=request.getParameter("Matricula");
        sNumBast=request.getParameter("NSerie");
        sKmRevis=request.getParameter("Kilometros");
        sKmRevis=miComun.ImportesABasedatos(sKmRevis);
        sMesRevis=request.getParameter("Meses");
        sMesRevis=miComun.ImportesABasedatos(sMesRevis);
        sNotas=request.getParameter("Notas");
        sRotulado=request.getParameter("Rotulado");
        sAutorAparc=request.getParameter("Autoriza");
        sCV=request.getParameter("CVFiscales");
        sCV=miComun.ImportesABasedatos(sCV);
        sColor=request.getParameter("Color");
        ////System.out.println("m05b - GrabarVarios: COLOR: " + sColor);
        sExpte=request.getParameter("Expdte");
        sInf1=request.getParameter("Inf1");
        ////System.out.println("m05b - GrabarVarios: INFORM 1: " + sInf1);
        sInf2=request.getParameter("Inf2");
        ////System.out.println("m05b - GrabarVarios: INFORM 2: " + sInf2);

		try{
			m05bConexion miConex = new m05bConexion();
			conn = miConex.getConnection();
			if (accion.equals(m05bConstantes.ACC_ACTUALIZAR))  {
				// Se inserta un registro en el histórico de vehículos
					// Para ello se recupera de BD la descripción anterior del vehiculo
			   sql = "select " + m05bConstantes.COL_34_FGARANTIA + ", " + m05bConstantes.COL_34_KMREVIS + 
			   		", " + m05bConstantes.COL_34_MESREVIS + ", " + m05bConstantes.COL_34_ROTULADO + 
			   		", " + m05bConstantes.COL_34_COLOR + ", " + m05bConstantes.COL_34_EXPDTE + 
			   		", " + m05bConstantes.COL_34_NSERIE + ", " + m05bConstantes.COL_34_AUTORI_APAR + 
			   		", " + m05bConstantes.COL_34_CV + ", " + m05bConstantes.COL_34_INF1 + 
			   		", " + m05bConstantes.COL_34_INF2 + ", " + m05bConstantes.COL_34_NOTA + 
					" from " + m05bConstantes.TAB_VEHICULOS  +
				    " where " +  m05bConstantes.COL_34_MATRICULA + " = '" + sMatricula + "'" ;
		       ////System.out.println("SQL VEHICULOS: " + sql );
		       	pstmt = conn.prepareStatement(sql);
		   		rs = pstmt.executeQuery();
		   		if (rs.next()){
	       	    			if (rs.getDate(1) != null)
	       	    				fGarantia = formatterDate.format(rs.getDate(1));
	       	    			sKmRevis = rs.getString(2);
	       	    			if (sKmRevis == null)
	       	    				sKmRevis = "";
	       	    			sMesRevis = rs.getString(3);
	       	    			if (sMesRevis == null)
	       	    				sMesRevis = "";
	       	    			sRotulado = rs.getString(4);
	       	    			sColor = rs.getString(5);
	       	    			sExpte = rs.getString(6);
	       	    			sNSerie = rs.getString(7);
							sAutorAparc = rs.getString(8);
							sCV = rs.getString(9);
							sInf1 = rs.getString(10);
							sInf2 = rs.getString(11);
							sNotas = rs.getString(12);
	           }
	           	id = miID.getNextId(m05bConstantes.TAB_HIST_VEHICULOS, m05bConstantes.COL_44_ID);
				// Ejecutar la inserción de los datos obtenidos
					   sql = " insert into " + m05bConstantes.TAB_HIST_VEHICULOS  + " (" +
							    	  m05bConstantes.COL_44_ID + ", " + m05bConstantes.COL_44_MATRICULA + 
									", " + m05bConstantes.COL_34_FGARANTIA + ", " + m05bConstantes.COL_34_KMREVIS + 
							   		", " + m05bConstantes.COL_34_MESREVIS + ", " + m05bConstantes.COL_34_ROTULADO + 
							   		", " + m05bConstantes.COL_34_COLOR + ", " + m05bConstantes.COL_34_EXPDTE + 
							   		", " + m05bConstantes.COL_34_NSERIE + ", " + m05bConstantes.COL_34_AUTORI_APAR + 
							   		", " + m05bConstantes.COL_34_CV + ", " + m05bConstantes.COL_34_INF1 + 
							   		", " + m05bConstantes.COL_34_INF2 + ", " + m05bConstantes.COL_34_NOTA +  
									", " + m05bConstantes.COL_44_FCAMBIO + ") " +
						   	  " values (" + id + ", '" + sMatricula + "', '" + sKmRevis + "', '" + sMesRevis + "', " + sRotulado + 
							  ", to_date('" + fGarantia + "','dd/mm/yyyy')" + sColor + "','" + sNSerie + "', '" + sExpte + 
							  "', '" + sAutorAparc + "', '" + sCV + "', '" + sInf1 + "', '" + sInf2 + "', sysdate )";

					    ////System.out.println("m05b - Grabar Vehiculos: INSERT-44: " + sql );
					    
					    pstmt = conn.prepareStatement(sql);
						pstmt.executeUpdate();
				// Se actualiza el registro actual del vehículo
				
				
			       pstmt = conn.prepareStatement("update " +m05bConstantes.TAB_VEHICULOS+
					" set "+m05bConstantes.COL_34_FGARANTIA+" = TO_DATE(?,'YYYYMMDDHH24MISS')" +
                    " , "+m05bConstantes.COL_34_KMREVIS+" = ? "+
                    " , "+m05bConstantes.COL_34_MESREVIS+" = ? "+
                    " , "+m05bConstantes.COL_34_ROTULADO+" = ? "+
                    " , "+m05bConstantes.COL_34_COLOR+" = ? "+
                    " , "+m05bConstantes.COL_34_EXPDTE+" = ? "+
                    " , "+m05bConstantes.COL_34_NSERIE+" = ? "+
                    " , "+m05bConstantes.COL_34_AUTORI_APAR+" = ? "+
                    " , "+m05bConstantes.COL_34_CV+" = ? "+
                    " , "+m05bConstantes.COL_34_INF1+" = ? "+
                    " , "+m05bConstantes.COL_34_INF2+" = ? "+
                    " , "+m05bConstantes.COL_34_NOTA+" = ? "+
					" where	"+m05bConstantes.COL_34_MATRICULA+" = ? ");

				pstmt.setString(1, sFecha);
                pstmt.setString(2, sKmRevis);
                pstmt.setString(3, sMesRevis);
                pstmt.setString(4, sRotulado);
                pstmt.setString(5, sColor);
                pstmt.setString(6, sExpte);
				pstmt.setString(7, sNumBast);
                pstmt.setString(8, sAutorAparc);
                pstmt.setString(9, sCV);
				pstmt.setString(10, sInf1);
                pstmt.setString(11, sInf2);
                pstmt.setString(12, sNotas);
                pstmt.setString(13, sMatricula);

			}

			pstmt.executeUpdate();
			
			//Si todo ha ido bien se actualizan los cambios en la BD
		    conn.commit();
			
			response.sendRedirect("m05bVariosJsp.jsp?Matricula="+sMatricula);
		} catch (Exception SQLException) {
  			conn.rollback();  // Ha habido problemas, se deshacen todos los cambios
			miLog.addTraza(SQLException);
			response.sendRedirect("m05bError.jsp");
		} 	finally{
				if (pstmt != null)
					pstmt.close();
				if (rs != null)
					rs.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);
		}
	}
}

}