import sys
import urllib
import urllib2
import json

sys.path.append("scripts")

def link(address, taskname, objects):
    # Read out all symbol tables that are to be linked
    definers = {}
    tasks = {}
    def flush_data(data):
        if data:
            urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "set_input", "data": json.dumps(data), "taskname": taskname})), timeout=10).read()
        return []
    flush_data([3, "link_and_load"] + objects + ["", "main"])

    v = urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "get_output", "taskname": taskname}))).read()
    v = json.loads(v)
    if "OK" not in v:
        print(v)
        raise Exception("Linking error")

if __name__ == "__main__":
    if len(sys.argv) == 1:
        print("No taskname defined")
    else:
        address = sys.argv[1]
        taskname = sys.argv[2]
        objects = set(sys.argv[3:])

        if objects:
            link(address, taskname, objects)
        else:
            print("No files to link defined")
