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

def do_compile(address, filename, taskname, 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"

    # Create new task
    try:
        urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "set_input", "value": '"%s"' % taskname, "taskname": "task_manager"}))).read()
        subprocess.check_call([sys.executable, "hutn_compiler/compiler.py", filename, grammar, mode, taskname, modulename, filename, address] + optionals, cwd="interface/HUTN")
        return 0
    except:
        return 1

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