import sys
import urllib
import urllib2
import json

sys.path.append("scripts")

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

    v = urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "get_output", "username": username}))).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 username defined")
    else:
        address = sys.argv[1]
        username = sys.argv[2]
        objects = set(sys.argv[3:])

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