package paqueteDAO;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import paqueteBL.Backup;
import paqueteBL.Evento;
import paqueteBL.VM;
import paqueteBL.VMext;

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

    public void readFromRS(Backup b,ResultSet rs) throws Exception
    {
        b.setId(rs.getInt("idBackup"));
        b.setIdVM(rs.getInt("idVM"));
        b.setFecha(rs.getDate("inicio"));
    }

/*    public VMext read(int id) throws Exception
    {
        String sql="SELECT * FROM vm WHERE idvm='" + id + "'";
        Statement scSQL = null;
        ResultSet rsListaRegistros;
        Connection co=null;
        try
        {
        co=getConexion();
        scSQL=co.createStatement();
        //scSQL =  getStatement();
        rsListaRegistros = scSQL.executeQuery(sql);
        if(rsListaRegistros.next())
        {
            VMext vm = new VMext();
            readFromRS(vm,rsListaRegistros);
            return vm;
        }
        else
           return null;
        } finally
        {
            if(scSQL!=null) scSQL.close();
            if (co!=null) liberaConexion(co);
        }
    }
*/
    public void insert(Backup backup) throws Exception
    {
        Statement scSQL = null;
        ResultSet rsListaRegistros;
        Connection co=null;
        try
        {
        co=getConexion();
        scSQL=co.createStatement();
        String valores="";
        valores=concatena(valores,backup.getIdVM());
        valores=concatena(valores,backup.getFecha());
        valores="(null,"+valores+")";

        System.out.println(valores);

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

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

        rsListaRegistros = scSQL.executeQuery(sql);

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

    public List<Backup> findBackupsByVM(int id,int max) throws Exception
    {
        return findByQuery("Select * from Backup Where idvm="+id+" Order by inicio DESC LIMIT "+max);
    }

}

