import importlib
import sys
import os

from os.path import join as join_path
from xmlrpc.client import ServerProxy as RPCClient

root = os.path.dirname(os.getcwd())
sys.path.append(join_path(root, 'uncloud'))
secrets = importlib.import_module('uncloud.secrets')


class OpenNebula:
    def __init__(self, url, session_string):
        self.session_string = session_string
        self.client = RPCClient(secrets.OPENNEBULA_URL)

    def create_user(self, username, password, authentication_driver='', group_id=None):
        # https://docs.opennebula.org/5.10/integration/system_interfaces/api.html#one-user-allocate

        if group_id is None:
            group_id = []

        return self.client.one.user.allocate(
            self.session_string,
            username,
            password,
            authentication_driver,
            group_id
        )

    def chmod(self, vm_id, user_id=-1, group_id=-1):
        # https://docs.opennebula.org/5.10/integration/system_interfaces/api.html#one-vm-chown

        return self.client.one.vm.chown(self.session_string, vm_id, user_id, group_id)


one = OpenNebula(secrets.OPENNEBULA_URL, secrets.OPENNEBULA_USER_PASS)

# Create User in OpenNebula
# success, response, *_ = one.create_user(username='meow12345', password='hello_world')
# print(success, response)

# Change owner of a VM
# success, response, *_ = one.chmod(vm_id=25589, user_id=706)
# print(success, response)
