import subprocess
import sys
import threading
import time
import random
import urllib
import urllib2

MVK_PORT = 8001
MVK_ADDRESS = "http://localhost"
ADMIN_USER = "admin"
ADMIN_PASSWORD = "admin"
SETUP_USER = "setup_task"

address = "%s:%s" % (MVK_ADDRESS, MVK_PORT)

# Compile the Statechart first
subprocess.check_call([sys.executable, "-m", "sccd.compiler.sccdc", "-p", "threads", "server.xml"], cwd="hybrid_server")

# Start up the MvK as a subprocess
try:
    obj = subprocess.Popen([sys.executable, "run_mvk_server.py", str(MVK_PORT), "--kernel=baseline-jit"], cwd="hybrid_server")

    # Compile all MvC code
    subprocess.call([sys.executable, "scripts/execute_model.py", address, SETUP_USER, "bootstrap/*.alc", "core/*.alc", "core/*.mvc"])

    # Set the admin taskname and password
    urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "set_input", "value": '"%s"' % ADMIN_USER, "taskname": SETUP_USER}))).read()
    urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "set_input", "value": '"%s"' % ADMIN_PASSWORD, "taskname": SETUP_USER}))).read()
    urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "set_input", "value": '"%s"' % ADMIN_PASSWORD, "taskname": SETUP_USER}))).read()
    urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "set_input", "value": '"exit"', "taskname": SETUP_USER}))).read()

    while 1:
        time.sleep(1)
finally:
    try:
        obj.terminate()
        time.sleep(1)
        if not obj.poll():
            obj.kill()
    except:
        pass
