from config import *
import base64
import time
import lxc

def get_version():
  vlxc = lxc.version
  vlibvirt = str(libvirt.getVersion()/1000000) #1000000 * major + 1000 * minor + release
  vhype = hype_version
  return vlxc, vlibvirt, vhype


def set_memory(vm_name,memory_new):
  dom = conn.lookupByName(vm_name)
  dom.shutdown()
  time.sleep(3)
  alive=0
  while alive < 5:
      if dom.isActive():
          time.sleep(3)
          alive+=1
      else:
          alive=6
  if dom.isActive():
      dom.destroy()
  dom.setMaxMemory(memory_new)
  dom.setMemoryFlags(memory_new)
  dom.create()
  time.sleep(3)
  alive=0
  while alive < 3:
      if dom.isActive():
          alive=4
      else:
          time.sleep(3)
          alive+=1

def set_vcpu(vm_name,vcpu_new):
  dom = conn.lookupByName(vm_name)
  dom.shutdown()
  time.sleep(3)
  alive=0
  while alive < 5:
      if dom.isActive():
          time.sleep(3)
          alive+=1
      else:
          alive=6
  if dom.isActive():
      dom.destroy()
  dom.setVcpusFlags(vcpu_new,libvirt.VIR_DOMAIN_AFFECT_CONFIG | libvirt.VIR_DOMAIN_VCPU_MAXIMUM)
  dom.setVcpusFlags(vcpu_new,libvirt.VIR_DOMAIN_AFFECT_CONFIG | libvirt.VIR_DOMAIN_VCPU_CURRENT)
  dom.create()
  time.sleep(3)
  alive=0
  while alive < 3:
      if dom.isActive():
          alive=4
      else:
          time.sleep(3)
          alive+=1

def get_info_vm(vm_name):
  dom = conn.lookupByName(vm_name)
  state, maxmem, mem, cpus, cput = dom.info()
  return state, maxmem, mem, cpus, cput

#Screenshot
def get_screenshot(vm_name):
  dom = conn.lookupByName(vm_name)
  stream = conn.newStream()
  imageType = dom.screenshot(stream,0)
  file = "tmp_screen_" + dom.name()
  fileHandler = open(file, 'wb')
  streamBytes = stream.recv(262120)
  while streamBytes != b'':
    fileHandler.write(streamBytes)
    streamBytes = stream.recv(262120)
  fileHandler.close()
  stream.finish()
  with open(file, "rb") as f:
    data = base64.b64encode(f.read())
  os.remove(file)
  return data

#Autostart

def get_autostart(vm_name):
  dom = conn.lookupByName(vm_name)
  return dom.autostart()

def set_autostart(vm_name):
  dom = conn.lookupByName(vm_name)
  dom.setAutostart(1)

def unset_autostart(vm_name):
  dom = conn.lookupByName(vm_name)
  dom.setAutostart(0)

