
package paqueteDAO;

import java.sql.Connection;
import java.util.Date;
import java.sql.ResultSet;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import paqueteBL.Evento;
import paqueteBL.VM;
import paqueteBL.VMext;


/**
 *
 * @author Administrador
 */
public class EventoDAO extends BaseDAO{

    public void readFromRS(Evento evento,ResultSet rs) throws Exception
    {
        evento.setId(rs.getInt("idEvento"));
        evento.setIdHost(rs.getInt("idHost"));
        evento.setIdVM(rs.getInt("idVM"));
        evento.setFecha(rs.getTimestamp("fecha"));
        evento.setEvento(rs.getString("evento"));
    }


    public void insert(Evento evento) throws Exception
    {
        Statement scSQL = null;
        ResultSet rsListaRegistros;
        Connection co=null;
        try
        {
        co=getConexion();
        scSQL=co.createStatement();
        String valores="";
        valores=concatena(valores,evento.getIdVM());
        valores=concatena(valores,evento.getIdHost());
        valores=concatena(valores,evento.getEvento());
        valores=concatena(valores,evento.getFecha());
        valores="(null,"+valores+")";

        System.out.println(valores);

        scSQL.executeUpdate("INSERT INTO evento (idevento,idvm,idhost,evento,fecha) values "+valores);
        rsListaRegistros = scSQL.executeQuery("SELECT LAST_INSERT_ID();");
        rsListaRegistros.next();
        evento.setId(rsListaRegistros.getInt(1));
        } finally
        {
            if(scSQL!=null) scSQL.close();
            if (co!=null) liberaConexion(co);
        }
    }

    public List<Evento> findByQuery(String sql) throws Exception
    {
        List<Evento> lista=new ArrayList<Evento>();
        Statement scSQL = null;
        ResultSet rsListaRegistros;
        Connection co=null;
        try
        {
        co=getConexion();
        scSQL=co.createStatement();

        rsListaRegistros = scSQL.executeQuery(sql);

        while(rsListaRegistros.next())
        {
            Evento evento=new Evento();
            readFromRS(evento,rsListaRegistros);
            lista.add(evento);
        }
        return lista;
        } finally
        {
            if(scSQL!=null) scSQL.close();
            if (co!=null) liberaConexion(co);
        }
    }


    public List<Evento> findEventosByVM(int id,int max) throws Exception
    {
        return findByQuery("Select * from Evento Where idVM="+id+" Order by fecha DESC  LIMIT "+max);
    }

    public List<Evento> findEventosByHost(int id,int max) throws Exception
    {
        return findByQuery("Select * from Evento Where idHost="+id+" Order by fecha DESC LIMIT "+max);
    }

    public List<Evento> findEventosByPool(int max) throws Exception
    {
        return findByQuery("Select * from Evento Order by fecha DESC  LIMIT "+max);
    }

}

