#!/usr/bin/env python3

import os
import subprocess
import time
import string
import random

agent_process=None

def agent_cleanup():
    if os.path.exists("/tmp/usp.db"):
        os.remove('/tmp/usp.db')

    if os.path.exists("out.log"):
        os.remove('out.log')

def agent_start():
    a_cmd = ['obuspa', '-p', '-v 0', '-r', '/tmp/agent_default_reset.txt', '-l', 'out.log']
    agent_cleanup()
    agent_process = subprocess.Popen(a_cmd)
    # wait for obuspa to start
    time.sleep(5)

def agent_stop():
    os.system("obuspa -c stop >/dev/null 2>&1")
    if agent_process != None:
        agent_process.kill();

def cli(op, params="", bootstrap=False, args=[]):
    cmd = ['./obuspa', '-c']
    cmd.append(op)
    if params:
        cmd.append(params)
    if args:
        cmd = cmd + args

    if bootstrap:
        agent_start()

    out = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    stdout,stderr = out.communicate()

    if bootstrap:
        agent_stop()

    if stderr is not None:
        print("Error while processing request: obuspa -c " + op)
        print(stderr)

    return stdout.decode('utf-8').strip();


def clear_subscription():
    return cli("del", "Device.LocalAgent.Subscription.*")

def create_subscription(NotifType, ReferenceList):
    ID = ''.join(random.choices(string.ascii_uppercase + string.digits, k = 5))
    inst = cli("add", "Device.LocalAgent.Subscription.").split(' ')[1]
    cli("set", args = [inst + '.Enable', 'true'])
    cli("set", args = [inst + '.ID', ID])
    cli("set", args = [inst + '.NotifType', NotifType])
    cli("set", args = [inst + '.ReferenceList', ReferenceList])

    return inst

def test_controller(input_file, bootstrap=False):
    c_cmd = ['obuspa_test', '-f', '/tmp/usp_test.db', '-r', '/tmp/controller_default_reset.txt', '-x', input_file]
    agent_out = None

    log = ""

    if bootstrap:
        agent_start()

    process = subprocess.run(c_cmd, check=True)

    if bootstrap:
        log="out.log"
    else:
        log="/tmp/output.log"

    if os.path.exists(log):
        with open(log, "r") as f:
            agent_out = f.read()

    if bootstrap:
        agent_stop()

    return agent_out.__str__().strip();

