/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package paqueteVIX;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
import java.util.logging.Level;
import java.util.logging.Logger;
import paqueteBL.Host;
import paqueteBL.VM;
import paqueteBL.VMext;


public class VIX extends Thread{

    private List<OP> asincronas=new ArrayList<OP>();
//Process miProceso = Runtime.getRuntime().exec("cmd.exe /C dir");
//Process miProceso = Runtime.getRuntime().exec("ls -l");

    public void encolaOP_asincronona(OP op)
    {
        asincronas.add(op);
    }


    public void procesaPila()
    {
        OP op=asincronas.get(0);
        System.out.println("operacion:"+op.getOperacion());
        if (op.getOperacion().equals("START_VM")) startVM((VMext)op.getObjeto());
        else if (op.getOperacion().equals("STOP_VM")) stopVM((VMext)op.getObjeto());
        else if (op.getOperacion().equals("PAUSE_VM")) pauseVM((VMext)op.getObjeto());
        else if (op.getOperacion().equals("SNAPSHOT")) snapshot((VMext)op.getObjeto());
        else if (op.getOperacion().equals("DELETE_SNAPSHOT")) delete_snapshot((VMext)op.getObjeto());
        else if (op.getOperacion().equals("CLONE")) cloneVM((VMext)op.getObjeto(),(String)op.getParamsAux());
        else if (op.getOperacion().equals("REGISTER")) registerVM((VMext)op.getObjeto(),(Host)op.getParamsAux());
        else if (op.getOperacion().equals("UNREGISTER")) unregisterVM((VMext)op.getObjeto());
        asincronas.remove(0);
    }

    public void run()
    {
        while(asincronas.size()>0)
        {
            procesaPila();
        }
    }



public static StringWriter executeCommand ( String command, boolean flagbackground)
{
    System.out.println(command);

StringWriter sw = new StringWriter();
// Definimos la cadena del interprete de comandos del sistema
String commandShell=null;

// Recuperamos el sistema operativo
String osName = System.getProperty ( "os.name" );

// Cargamos la cadena del interprete de comandos según el sistema operativo y el comando a ejecutar
if ( osName.equals ("Windows NT") )
commandShell = "cmd.exe /C " + command;
else if ( osName.equals ("Windows 95") || osName.equals ("Windows 98") )
commandShell = "start " + command;
else
{
// En UNIX y LUNUX podemos lanzar el proceso en background sufijandolo con &
if (flagbackground)
commandShell = "" + command +" &" ;
else
commandShell = "" + command ;
}

// Lanzamos el proceso
try
{
Process proc = Runtime.getRuntime ().exec (commandShell);
BufferedReader brStdOut = new BufferedReader(new InputStreamReader(proc.getInputStream()));
BufferedReader brStdErr = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
String str=null;
while ((str = brStdOut.readLine())!=null)
{
System.out.println (str);
sw.append(str+"\n");
}
brStdOut.close();
brStdErr.close();
}
catch (IOException eproc)
{
System.out.println ("Error to execute the command : "+eproc);
return null;
}
return sw;
}

public List<VMext> findVMbyHost(Host host)
{
    StringWriter sw=VIX.executeCommand("vmrun "+ host.getStrConexion()+" LISTREGISTEREDVM ",false);
    if (sw.toString().contains("Error")) return null;
    String activas=VIX.executeCommand("vmrun "+ host.getStrConexion()+" LIST ",false).toString();
    List lstMaquinas=new ArrayList<VM>();
    String maquinas[]=sw.toString().split("\n");
    int i;
    int x;
    int y;
    String dataRep;
    String pathRep;
    String path;
    String nombre;
    for(i=1;i<maquinas.length;i++)
    {
        x=maquinas[i].indexOf("/");
        y=maquinas[i].indexOf("]", x+1);
        dataRep=maquinas[i].substring(1, x);
        pathRep=maquinas[i].substring(x+1, y);
        x=maquinas[i].lastIndexOf("/");
        path=maquinas[i].substring(y+2, x);
        nombre=maquinas[i].substring(x+1,maquinas[i].length()-4);
        VMext maquina=new VMext(dataRep,pathRep,path,nombre);
        maquina.setHost(host);
        if (activas.contains(maquina.getNombre()+".vmx"))
        {
            //System.out.println("ACTIVA:"+maquina.getNombre());
            maquina.setEstado(VM.ESTADO_START);
        }
        else
        {
            //System.out.println("INACTIVA:"+maquina.getNombre());
            maquina.setEstado(VM.ESTADO_STOP);
        }
            
        lstMaquinas.add(maquina);
    }
    return lstMaquinas;
}


static public void startVM(VMext vm)
{
    StringWriter sw=VIX.executeCommand("vmrun "+ vm.getHost().getStrConexion()+" START "+vm.getNombreCompleto(),false);
}

static public void stopVM(VMext vm)
{
    StringWriter sw=VIX.executeCommand("vmrun "+ vm.getHost().getStrConexion()+" STOP "+vm.getNombreCompleto(),false);
}

static public void pauseVM(VMext vm)
{
    StringWriter sw=VIX.executeCommand("vmrun "+ vm.getHost().getStrConexion()+" PAUSE "+vm.getNombreCompleto(),false);
}

static public void cloneVM(VMext vm,String target)
{
    StringWriter sw=VIX.executeCommand("vmrun "+ vm.getHost().getStrConexion()+" CLONE "+vm.getNombreCompleto() + " "+target,false);
}

static public void snapshot(VMext vm)
{
    StringWriter sw=VIX.executeCommand("vmrun "+ vm.getHost().getStrConexion()+" SNAPSHOT "+vm.getNombreCompleto()+" SNAPBK",false);
}

static public void delete_snapshot(VMext vm)
{
    StringWriter sw=VIX.executeCommand("vmrun "+ vm.getHost().getStrConexion()+" DELETESNAPSHOT "+vm.getNombreCompleto()+" SNAPBK",false);
}

static public void registerVM(VMext vm,Host host)
{
    StringWriter sw=VIX.executeCommand("vmrun "+ host.getStrConexion()+" REGISTER "+vm.getNombreCompleto(),false);
}

static public void unregisterVM(VMext vm)
{
    StringWriter sw=VIX.executeCommand("vmrun "+ vm.getHost().getStrConexion()+" UNREGISTER "+vm.getNombreCompleto(),false);
}


}


