import sys
import os
import urllib2
import urllib
import subprocess
import time

def do_compile(address, filename, username, modulename, mode, optionals=['--debug'], grammar=""):
    filename = os.path.realpath(filename)
    if grammar == "":
        if mode[0] == "M":
            # Load model grammar
            grammar = "grammars/modelling.g"
        else:
            # Load AL grammar
            grammar = "grammars/actionlanguage.g"
    while 1:
        try:
            # Create new user
            urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "set_input", "value": '"%s"' % username, "username": "user_manager"}))).read()
            subprocess.check_call([sys.executable, "hutn_compiler/compiler.py", filename, grammar, mode, username, modulename, filename, address] + optionals, cwd="interface/HUTN")
            break
        except:
            time.sleep(0.01)
    return 0

if __name__ == "__main__":
    if len(sys.argv) != 6:
        sys.stderr.write("Expected different parameters!\n")
        sys.stderr.write("    %s address filename username modulename mode\n" % sys.argv[0])
        sys.exit(1)
    else:
        address = sys.argv[1]
        filename = sys.argv[2]
        username = sys.argv[3]
        modulename = sys.argv[4]
        mode = sys.argv[5]
        
        sys.exit(do_compile(address, filename, username, modulename, mode))
