import random
import sys
import multiprocessing

from compile import do_compile
from link_and_load import link_and_load
from make_parallel import main

models = []
code = []

address = sys.argv[1]
username = sys.argv[2]

for f in sys.argv[3:]:
    if f.endswith(".mvc"):
        models.append(f)
    elif f.endswith(".alc"):
        code.append(f)
    else:
        print("Unknown file format for file " + f)
        print("Requires either .mvc or .alc")

def initialize_SCD():
    import urllib2
    import urllib
    import json
    username = random.random()
    urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "set_input", "value": '"%s"' % username, "username": "user_manager"}))).read()

    data = []
    data.append(4)
    data.append("initialize_SCD")
    data.append("models/SimpleClassDiagrams")
    data.append("exit")
    data.append(2)

    print("Initializing SCD")
    urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "set_input", "data": json.dumps(data), "username": username}))).read()
    urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "get_output", "username": username}))).read()
    print("Initialized!")

def do_compile_wrapper(filename, mode, grammar):
    do_compile(address, filename, str(random.random()), filename, mode, ["--debug"], grammar=grammar)

# Parse all models and upload them
initialize_SCD()

for m in models:
    do_compile_wrapper(m, "MO", "grammars/modelling.g")

#p = multiprocessing.Pool(multiprocessing.cpu_count() * 2)
#p.map(lambda i: do_compile_wrapper(i, "PO", grammar="grammars/actionlanguage.g"), code)
#link_and_load(address, username, code)
main(address, username, code)
