package festivoServlet;

import java.io.IOException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Calendar;

import m05bClasses.m05bConexion;
import m05bClasses.m05bConstantes;
import m05bClasses.m05bFileLog;
import m05bClasses.m05bGenerarClave;

	
	/**
 * Inserte aquí la descripción del tipo.
 * Fecha de creación: (15/12/05)
 */
public class m05bGenerarCalServlet extends javax.servlet.http.HttpServlet {m05bFileLog miLog = new m05bFileLog();
/**
 * Process incoming HTTP GET 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) {


	java.sql.Connection conn = null;
	PreparedStatement pstmt = null;
	ResultSet rs = null;
	
	try	{
		// Insert user code from here.

		int ejer, contdiaSemanas=0, id=0,  mes, diaSemana;
		String sql="", descripcion="",edescripcion="", ejercicio;
		
		m05bFileLog miLog = new m05bFileLog();
		m05bGenerarClave miClave = new m05bGenerarClave();
		m05bConexion miConex = new m05bConexion();

		conn = miConex.getConnection();	
		conn.setAutoCommit(false);
		ejercicio = request.getParameter("Ejer");
		ejer=Integer.valueOf(ejercicio).intValue();
		
		id = miClave.getNextId(m05bConstantes.TAB_FESTIVOS, m05bConstantes.COL_08_CODIGO);
        Calendar miCalendario = Calendar.getInstance();
        miCalendario.set(ejer, 0, 1);
		
        //Borro todos los dias de ese ejercicio de la tabla de calendario
        sql="delete " + m05bConstantes.TAB_FESTIVOS +
		" where TO_CHAR("+m05bConstantes.COL_08_FECHA +", 'YYYY') = '" +ejer+"'" ;
		
        miLog.addTraza("","Calendario","DELETE-SQL: " + sql, m05bConstantes.LOG_NIVEL_BAJO);
		pstmt = conn.prepareStatement(sql);
		pstmt.executeUpdate();
		if (pstmt != null)
			pstmt.close();
		
        while (miCalendario.get(Calendar.YEAR) == ejer) {
			mes=miCalendario.get(Calendar.MONTH) +1;
			//miLog.addTraza("","Calendario","FECHA: " + miCalendario.get(Calendar.DATE) + "/" + mes + "/" + ejer, m05bConstantes.LOG_NIVEL_BAJO );
        	
        	diaSemana = miCalendario.get(Calendar.DAY_OF_WEEK);
        	if ( diaSemana == Calendar.SATURDAY  ) {
        		descripcion="SABADO";
        		edescripcion="LARUNBATA";
			} else if (diaSemana == Calendar.SUNDAY )  {
        		descripcion="DOMINGO";
        		edescripcion="IGANDEA";
			}
        	if ( (diaSemana == Calendar.SATURDAY) || (diaSemana == Calendar.SUNDAY)  )   {
					mes=miCalendario.get(Calendar.MONTH) +1;
					sql="insert into " + m05bConstantes.TAB_FESTIVOS +
								" (" + m05bConstantes.COL_08_CODIGO + 
								", " + m05bConstantes.COL_08_FECHA + 
								", "+ m05bConstantes.COL_08_DESCRIPCION + ",E"+ m05bConstantes.COL_08_DESCRIPCION +") " +
								" values " +
								" (" + id + ", to_date('" + miCalendario.get(Calendar.DATE) + "/" + mes + "/" + ejer + "','dd/mm/yyyy'), '" + descripcion + "','"+edescripcion+"')" ;
					miLog.addTraza("","Calendario","INSERT-SQL: " + sql, m05bConstantes.LOG_NIVEL_BAJO);
					pstmt = conn.prepareStatement(sql);
			    	pstmt.executeUpdate();
					if (pstmt != null)
						pstmt.close();
			}
			miCalendario.add(Calendar.DATE,1);
			++id;
			miLog.addTraza("","Calendario","ID: " + id, m05bConstantes.LOG_NIVEL_BAJO);
        }
        conn.commit();
		miLog.addTraza("","Calendario","Antes SendRedirect ", m05bConstantes.LOG_NIVEL_BAJO);
		response.sendRedirect("m05bRelFestivosJsp.jsp?Ejer="+ejer);
	} catch(Throwable theException)	{
		try {
			// uncomment the following line when unexpected exceptions
			// are occuring to aid in debugging the problem.
			//miLog.addTraza(theException);
			conn.rollback();
		} catch (SQLException e) {
			try {
				response.sendRedirect("m05bError.jsp");
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				miLog.addTraza(e1);
			}
		}
	} finally  {
			try {
					if (rs != null)
						rs.close();
					if (pstmt != null)
						pstmt.close();
					if (conn != null)
						conn.close();
			} catch (Exception SQLException) {
				try {
					response.sendRedirect("m05bError.jsp");
				} catch (IOException e) {
					// TODO Auto-generated catch block
					miLog.addTraza(e);
				}
			}
	}
}
}