/*
 * Creado el 11-mar-04
 *
 * Para cambiar la plantilla para este archivo generado vaya a
 * Ventana&gt;Preferencias&gt;Java&gt;Generación de código&gt;Código y comentarios
 */
package es.ejie.frmk.presentacion.sesiondatos.utilidades;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;

/**
 * @version 1.0
 * Fecha: 11-mar-04
 */
public class Q70BorradoBDPorFecha
{
	private Connection conn;
	protected String dbDriver = null;
	protected String dbServer = null;
	protected String dbLogin = null;
	protected String dbPassword = null;

	protected String selectSentence = null;
	protected String deleteSentence = null;

	protected String claveSQL = null;
	protected String datosSQL = null;

	protected long deleteDate = -1;
	
	public Q70BorradoBDPorFecha()
	{
		super();
	}

	public void setClaveSQL(String aClaveSQL)
	{
		claveSQL = aClaveSQL;
	}

	public void setDatosSQL(String aDatosSQL)
	{
		datosSQL = aDatosSQL;
	}

	public void setDbDriver(String aDbDriver)
	{
		dbDriver = aDbDriver;
	}

	public void setDbLogin(String aDbLogin)
	{
		dbLogin = aDbLogin;
	}

	public void setDbPassword(String aDbPassword)
	{
		dbPassword = aDbPassword;
	}

	public void setDbServer(String aDbServer)
	{
		dbServer = aDbServer;
	}

	public void setDeleteDate(long aDeleteDate)
	{
		deleteDate = aDeleteDate;
	}

	public void setDeleteSentence(String aDeleteSentence)
	{
		deleteSentence = aDeleteSentence;
	}

	public void setSelectSentence(String aSelectSentence) {
		selectSentence = aSelectSentence;
	}

	public void borrarSesiones()
	{
		if (existenParametrosNulos())
			throw new RuntimeException("Clase incorrectamente inicializada, faltan parametros.");
		initializeBD();
		tratamientoBDSesiones();
	}

	public void borraSinSelect()
	{
		if (existenParametrosNulosPila())
			throw new RuntimeException("Clase incorrectamente inicializada, faltan parametros.");
		initializeBD();
		tratamientoBDPila();
	}

	protected Connection getConnection() throws java.sql.SQLException
	{
		try
		{
			Class.forName(dbDriver);
		}
		catch (ClassNotFoundException cnfe)
		{
			throw new java.sql.SQLException(cnfe.getMessage() + "..." + cnfe.getClass().getName());
		}
		return DriverManager.getConnection(dbServer, dbLogin, dbPassword);
	}

	private void tratamientoBDSesiones()
	{
		PreparedStatement pstmt = null;
		ResultSet rdo = null;

		try
		{
			pstmt = conn.prepareStatement(selectSentence);
			rdo = pstmt.executeQuery();

			while (rdo.next())
			{
				borrarIdContexto(rdo);
			}
		}
		catch (SQLException e)
		{
			trazaError("Error:"+e.getClass()+","+e.getMessage(),e);
		}
		catch (Throwable e)
		{
			trazaError("Error:"+e.getClass()+","+e.getMessage(),e);
		}
		finally
		{
			try
			{
				if (rdo != null)
					rdo.close();
			}
			catch (SQLException e)
			{}
			try
			{
				if (pstmt != null)
					pstmt.close();
			}
			catch (SQLException e)
			{}
			try
			{
				if (conn != null)
					conn.close();
			}
			catch (SQLException e)
			{}
		}
	}

	protected boolean existenParametrosNulos(){
		return (dbDriver == null || dbServer == null || dbLogin == null	|| dbPassword == null || selectSentence == null 
			|| deleteSentence == null || claveSQL == null || datosSQL == null || deleteDate == -1);
	}
	
	protected boolean existenParametrosNulosPila(){
		return (dbDriver == null || dbServer == null || dbLogin == null	|| dbPassword == null  
				|| deleteSentence == null || deleteDate == -1);
	}

	private void initializeBD()
	{
		try
		{
			conn = getConnection();
			DatabaseMetaData meta = conn.getMetaData();
			trazaInfo("La version del driver JDBC es: " + meta.getDriverName() + ": " + meta.getDriverVersion());
		}
		catch (Exception e)
		{
			trazaError("Error en initializeBD():"+e.getClass()+","+e.getMessage(),e);
		}
	}
	

	private void borrarIdContexto(ResultSet rdo) throws SQLException
	{
		try
		{
			String idContexto = rdo.getString(claveSQL).trim();
			ObjectInputStream si = new ObjectInputStream(rdo.getBinaryStream(datosSQL));
			Long lastAccessTime = (Long) si.readObject();
			trazaInfo("Registro..." + idContexto + "..." + lastAccessTime + "..." + new Date(lastAccessTime.longValue()));

			if (lastAccessTime.longValue() <= System.currentTimeMillis() - deleteDate)
			{
				trazaInfo("...Borrando..." + idContexto + "..." + lastAccessTime + "..." + new Date(lastAccessTime.longValue()));
				borrarIdContexto(idContexto);
			}

		}
		catch (NullPointerException e)
		{
			trazaError("Error:"+e.getClass()+","+e.getMessage(),e);
		}
		catch (IOException e)
		{
			trazaError("Error:"+e.getClass()+","+e.getMessage(), e);
		}
		catch (ClassNotFoundException e)
		{
			trazaError("Error:"+e.getClass()+","+e.getMessage(),e);
		}
	}

	private void borrarIdContexto(String idContexto)
	{
		PreparedStatement pstmt = null;

		try
		{
			pstmt = conn.prepareStatement(deleteSentence);
			pstmt.setString(1, idContexto);
			int filasBorradas = pstmt.executeUpdate();
			trazaInfo("...Filas borradas del contexto '" + idContexto + "': " + filasBorradas);
		}
		catch (SQLException e)
		{
			trazaError("Error:"+e.getClass()+","+e.getMessage(),e);
		}
		catch (Throwable e)
		{
			trazaError("Error:"+e.getClass()+","+e.getMessage(), e);
		}
		finally
		{
			try
			{
				if (pstmt != null)
					pstmt.close();
			}
			catch (SQLException e)
			{}
		}
	}

	private void tratamientoBDPila()
	{
		PreparedStatement pstmt = null;

		try
		{
			pstmt = conn.prepareStatement(deleteSentence);
			pstmt.setDate(1, new java.sql.Date(System.currentTimeMillis() - deleteDate));
			int filasBorradas = pstmt.executeUpdate();
			trazaDebug("...Filas borradas de la pila: " + filasBorradas);		
		}
		catch (SQLException e)
		{
			trazaError("Error:"+e.getClass()+","+e.getMessage(),e);
		}
		catch (Throwable e)
		{
			trazaError("Error:"+e.getClass()+","+e.getMessage(),e);
		}
		finally
		{
			try
			{
				if (pstmt != null)
					pstmt.close();
			}
			catch (SQLException e)
			{}
			try
			{
				if (conn != null)
					conn.close();
			}
			catch (SQLException e)
			{}
		}
	}

	protected void traza(String traza){
		System.out.println(traza);
	}

	protected void trazaError(String traza) {
		traza(traza);
	}
	
	protected void trazaDebug(String traza) {
		traza(traza);	
	}
	
	protected void trazaWarn(String traza) {
		traza(traza);	
	}
	
	protected void trazaInfo(String traza) {
		traza(traza);	
	}
	
	protected void trazaFatal(String traza) {
		traza(traza);	
	}

	private void trazaGenerica(String traza, Throwable e) {
		traza(traza);
		e.printStackTrace();		
	}
	protected void trazaError(String traza, Throwable e) {
		trazaGenerica(traza,e);
	}
	
	protected void trazaDebug(String traza, Throwable e) {
		trazaGenerica(traza,e);	
	}
	
	protected void trazaWarn(String traza, Throwable e) {
		trazaGenerica(traza,e);	
	}
	
	protected void trazaInfo(String traza, Throwable e) {
		trazaGenerica(traza,e);	
	}
	
	protected void trazaFatal(String traza, Throwable e) {
		trazaGenerica(traza,e);	
	}

}
