package gruposServlet;

/**
 * Date: May 5, 2004
 * Time: 8:26:16 AM
 */

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

import javax.servlet.http.HttpSession;

import m05bBD.m05bGrupos;
import m05bClasses.m05bConexion;
import m05bClasses.m05bConstantes;
import m05bClasses.m05bFileLog;
public class m05bGrabarGruposServlet 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, sNombre, sRango="";
           	String accion, sql = "";
            java.sql.Connection conn=null;
            PreparedStatement pstmt = null;
            ResultSet rs = null;
            boolean finalizado = false;
           try

        {
            HttpSession session = request.getSession(true);

            m05bGrupos grupos = (m05bGrupos)session.getAttribute("m05bGrupos");
            sCodigo = request.getParameter("Codigo");
            grupos.setGru_codigo(sCodigo);
            sNombre=request.getParameter("Nombre").toUpperCase();
            String sNombreEu=request.getParameter("NombreEu").toUpperCase();
            grupos.setGru_nombre(sNombre);
            Enumeration e= request.getParameterNames();
            String aux="";
            while (e.hasMoreElements()){
                aux=(String)e.nextElement();
                if (aux.indexOf("chkBox")!=-1)
                 sRango=sRango+request.getParameter(aux)+",";

            }
            sRango=sRango.substring(0,sRango.length()-1);
            grupos.setGru_rango(sRango);
            accion=request.getParameter("Accion");


            try{
                m05bConexion miConex = new m05bConexion();
                conn = miConex.getConnection();
                if (accion.equals(m05bConstantes.ACC_ACTUALIZAR))  {
                    pstmt = conn.prepareStatement(
                        "update	M0536T00 " +
                        "set	NOMBRE_36 = ? " +
                        ", ENOMBRE_36 = ?"+
                        " ,		RANG_36 = ? " +
                        "where	COD_GRUP_36 = ?");
                    pstmt.setString(1, sNombre);
                    pstmt.setString(2, sNombreEu);
                    pstmt.setString(3, sRango);
                    pstmt.setString(4, sCodigo);
                }
                else if (accion.equals(m05bConstantes.ACC_INSERTAR))  {
			// Chequear si ya existe un grupo de rangos con ese codigo
			   sql = "select 1  from M0536T00 where COD_GRUP_36 = '" + sCodigo + "'";
		       pstmt = conn.prepareStatement(sql);
		       //System.out.println("m05b - Grabar Grupos: SQL : " + sql);
			   rs = pstmt.executeQuery();
			   if (rs.next() == true){ 		
       	    			response.sendRedirect("m05bGruposJsp.jsp?Codigo=" + sCodigo + "&Mensaje=Existe");
       	    			finalizado = true;
			   } 
			   else {
	                    pstmt = conn.prepareStatement(
	                        "insert into	M0536T00 " +
	                        "(COD_GRUP_36, NOMBRE_36, RANG_36,ENOMBRE_36) " +
	                        " values " +
	                        "(? ,?, ? ,?)" );
	                    pstmt.setString(1, sCodigo);
	                    pstmt.setString(2, sNombre);
	                    pstmt.setString(3, sRango);
	                    pstmt.setString(4, sNombreEu);
				   }
                }
                else   {
                    pstmt = conn.prepareStatement(
                        "delete from 	M0536T00 " +
                        " where COD_GRUP_36 =  ? " );
                    pstmt.setString(1, sCodigo);
                }
                if(!finalizado){
	                pstmt.executeUpdate();
	                response.sendRedirect("m05bRelGruposJsp.jsp");
                }    
            } 	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)
        {
            miLog.addTraza(theException);
            try {
				response.sendRedirect("m05bError.jsp");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				miLog.addTraza(e);
			}
        }
    }
}