package gastosServlet;

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

import javax.servlet.http.HttpSession;

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

public class m05bGrabarGastosServlet 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 sql="", accion;
       String sCodigo, sTarjeta="", sFGasto="", sLitros="", sCodcpto="";
       java.util.Date fGasto=null;
       String sEstcif="", sEstncom="", sCargo="", sImporte="", sMatricula="";
       String sKilometros="", sHora, desde="", hasta="", asignacion="";

       m05bComun comun= new m05bComun();
	   java.sql.Connection conn=null;
	   PreparedStatement pstmt = null;
	   m05bFileLog miLog = new m05bFileLog();
       
       try  {   
			HttpSession session = request.getSession(true);
	        SimpleDateFormat dateFormater = new SimpleDateFormat("dd/MM/yyyy");
       	   
	        m05bGastos gastos = (m05bGastos)session.getAttribute("m05bGastos");
			sCodigo = request.getParameter("Codigo")==null?"":request.getParameter("Codigo");

			if (sCodigo.equals("NUEVO")) {
				m05bGenerarClave newCodigo = new m05bGenerarClave();
				sCodigo=""+newCodigo.getNextId(m05bConstantes.TAB_GASTOS, m05bConstantes.COL_09_CODIGO);
			}
			gastos.setGas_codigo(sCodigo);

	        sMatricula=request.getParameter("Matricula")==null?"":request.getParameter("Matricula").toUpperCase();
	        gastos.setGas_matricula(sMatricula);
			
			desde = (String) session.getAttribute("GastosDesde");
			hasta = (String) session.getAttribute("GastosHasta");
			asignacion = (String) session.getAttribute("GastosAsig");
			
			accion=request.getParameter("Accion");

			if (!(accion.equals(m05bConstantes.ACC_ELIMINAR))) {
				sTarjeta=request.getParameter("Tarjeta")==null?"":request.getParameter("Tarjeta").toUpperCase();
				gastos.setGas_tarjeta(sTarjeta);
				
				sFGasto=request.getParameter("Fecha");
		  		if (!(sFGasto.equals("")))
			  			fGasto = dateFormater.parse(sFGasto);
		        sHora=request.getParameter("Hora");
		        sFGasto=comun.FechaBD(sFGasto,sHora);
				gastos.setGas_fgasto(sFGasto);
		        sLitros=request.getParameter("Litros");
		        if (sLitros==null || sLitros.equals(""))
		        sLitros="";
		        gastos.setGas_litros(sLitros);
		        sCodcpto=request.getParameter("Concepto");
		        /*if (sCodcpto!=null || !sCodcpto.equals("")){
		          sCodcpto=sCodcpto.substring(0,sCodcpto.indexOf("-"));
		        }*/
		        gastos.setGas_codcpto(sCodcpto);
		        sEstcif=request.getParameter("CIF")==null?"":request.getParameter("CIF").toUpperCase();
		        gastos.setGas_estbcif(sEstcif);
		        sEstncom=request.getParameter("Comercio")==null?"":request.getParameter("Comercio").toUpperCase();
		        gastos.setGas_estnombre(sEstncom);
		        sCargo=request.getParameter("Cargo").toUpperCase();
		        gastos.setGas_cargo(sCargo);
		        sImporte=request.getParameter("Importe");
		        if ( (sImporte == null) || (sImporte.equals("")) )
		        	sImporte="0";
		        sImporte=comun.ImportesABasedatos(sImporte);
		        gastos.setGas_importe(sImporte);
		        sKilometros=request.getParameter("Km");
		        if (sKilometros==null || sKilometros.equals(""))
		        sKilometros="";
		        gastos.setGas_kilometros(sKilometros);

			}
			
			try{
					m05bConexion miConex = new m05bConexion();
					conn = miConex.getConnection();
					if (accion.equals(m05bConstantes.ACC_ACTUALIZAR))  {
								sql=" update	" +m05bConstantes.TAB_GASTOS+
								" set "+m05bConstantes.COL_09_IMPORTE+"	 = " + sImporte+
			                    ", "+m05bConstantes.COL_09_TARJETA+" = '"+sTarjeta+
			                    "', "+m05bConstantes.COL_09_FECHA+" = TO_DATE('" + sFGasto + "','YYYYMMDDHH24MISS')" + 
			                    ", "+m05bConstantes.COL_09_LITROS+" = REPLACE('"+sLitros+
			                    "','.',''), "+m05bConstantes.COL_09_CODCPTO+" = '"+sCodcpto+
			                    "', "+m05bConstantes.COL_09_ESTCIF+" = '"+sEstcif+
			                    "', "+m05bConstantes.COL_09_ESTNOM+" = '"+ sEstncom+
			                    "', "+m05bConstantes.COL_09_CARGO+" = '"+sCargo+
			                    "', "+m05bConstantes.COL_09_MATRICULA+" = '"+sMatricula+
			                    "', "+m05bConstantes.COL_09_KMGASTO+" = REPLACE('" +sKilometros+
								"','.','') where "+m05bConstantes.COL_09_CODIGO+"	 =  '"+sCodigo+"'";
			                pstmt = conn.prepareStatement(sql);
					} else if (accion.equals(m05bConstantes.ACC_INSERTAR))  {
							sql = "insert into " + m05bConstantes.TAB_GASTOS +
								" ("+m05bConstantes.COL_09_CODCPTO+","+m05bConstantes.COL_09_CODIGO+","+
			                    m05bConstantes.COL_09_TARJETA+","+m05bConstantes.COL_09_FECHA+","+
			                    m05bConstantes.COL_09_LITROS+","+m05bConstantes.COL_09_ESTCIF+","+
			                    m05bConstantes.COL_09_ESTNOM+","+m05bConstantes.COL_09_CARGO+","+
			                    m05bConstantes.COL_09_IMPORTE+","+m05bConstantes.COL_09_MATRICULA+","+
			                    m05bConstantes.COL_09_KMGASTO+") " +" values " +"('"+
								sCodcpto+"' ,'"+sCodigo+"','"+sTarjeta+ "', TO_DATE('" + sFGasto + "','YYYYMMDDHH24MISS')" + 
								" ,REPLACE('" + sLitros + "','.',''), '" + sEstcif+"','"+sEstncom+"','"+sCargo+"',"+sImporte+",'"+
								sMatricula+"',REPLACE('"+sKilometros +"','.','') )" ;
							pstmt = conn.prepareStatement(sql);
							//pstmt.setTimestamp(1, new Timestamp(fGasto.getTime()));
					} else   {
							pstmt = conn.prepareStatement(
								"delete from " +m05bConstantes.TAB_GASTOS+
								" where "+m05bConstantes.COL_09_CODIGO+" =  ? " );
							pstmt.setString(1, sCodigo);
					}
					pstmt.executeUpdate();
					
					response.sendRedirect("m05bRelGastosJsp.jsp?Codigo="+ asignacion +"&Desde="+desde+"&Hasta="+hasta+"&Matricula="+sMatricula);

			}  	catch (Exception SQLException) {
					miLog.addTraza(SQLException);
					response.sendRedirect("m05bError.jsp");
			} 	finally{
					if (pstmt != null)
						pstmt.close();
					if (conn != null)
						conn.close();
			}
	} catch(Throwable theException) {
		miLog.addTraza(theException);
		try {
			response.sendRedirect("m05bError.jsp");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			miLog.addTraza(e);
		}
	}
}

}