package modeloServlet;

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

import javax.servlet.http.HttpSession;

import m05bBD.m05bModelo;
import m05bClasses.m05bConexion;
import m05bClasses.m05bConstantes;
import m05bClasses.m05bFileLog;

/**
 * Inserte aquí la descripción del tipo.
 * Fecha de creación: (19/9/03)
 */
public class m05bGrabarModeloServlet 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, sMarca, sDescripcion;
       String accion, sql = "";
	   java.sql.Connection conn=null;
	   PreparedStatement pstmt = null;
	   ResultSet rs = null;
	   boolean finalizado = false;
       try	{

		HttpSession session = request.getSession(true);
		String persona = (String) session.getAttribute("persona");
		m05bFileLog miLog = new m05bFileLog();
		
        m05bModelo modelo = (m05bModelo)session.getAttribute("m05bModelo");
		sCodigo = request.getParameter("Codigo").toUpperCase();
		modelo.setMod_codigo(sCodigo);
		sMarca = request.getParameter("Marca");
		/*int iFinMarca = sMarca.indexOf("-");
		sMarca = sMarca.substring(0,iFinMarca);
		sMarca = sMarca.trim();*/
		modelo.setMod_marca(sMarca);
		sDescripcion = request.getParameter("Descripcion").toUpperCase();
		modelo.setMod_descripcion(sDescripcion);
		accion=request.getParameter("Accion");

		try{
			m05bConexion miConex = new m05bConexion();
			conn = miConex.getConnection();
			if (accion.equals(m05bConstantes.ACC_ACTUALIZAR))  {
				pstmt = conn.prepareStatement(
					"update	M0517T00 " + 
					"set	DESCRIP_17 = ?, MARCA_17 = ? " + 
					"where	COD_MOD_17 = ?");
					pstmt.setString(1, sDescripcion);
					pstmt.setString(2, sMarca);
					pstmt.setString(3, sCodigo);
			} else if (accion.equals(m05bConstantes.ACC_INSERTAR))  {
				// Chequear si ya existe un modelo con ese codigo
				   sql = "select 1  from M0517T00 where COD_MOD_17 = '" + sCodigo + "'";
				   miLog.addTraza(persona,"Grabar Modelo","SQL: " + sql, m05bConstantes.LOG_NIVEL_BAJO);
			       pstmt = conn.prepareStatement(sql);
				   rs = pstmt.executeQuery();
				   if (rs.next() == true) { 		
	       	    			response.sendRedirect("m05bModelosJsp.jsp?Codigo=" + sCodigo + "&Mensaje=Existe");
	       	    			finalizado = true;
				   } else {
						pstmt = conn.prepareStatement(
							"insert into	M0517T00 " + 
							"(COD_MOD_17, MARCA_17, DESCRIP_17) " + 
							" values " + 
							"(? ,?, ? )" );
						pstmt.setString(1, sCodigo);
						pstmt.setString(2, sMarca);
						pstmt.setString(3, sDescripcion);
				   }
			} else   {
					pstmt = conn.prepareStatement(
						"delete from 	M0517T00 " + 
						" where COD_MOD_17 =  ? " );
					pstmt.setString(1, sCodigo);
			}
			if(!finalizado){
				pstmt.executeUpdate();
				response.sendRedirect("m05bRelModelosJsp.jsp");
			}
			} 	catch (Exception SQLException) {
					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);
		}
	}
}
}