import sys
import urllib
import urllib2
import json

def flush_data(address, data, username):
    if data:
        urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "set_input", "data": json.dumps(data), "username": username})), timeout=10).read()
    return []

def link(address, username, objects):
    # Read out all symbol tables that are to be linked
    definers = {}
    users = {}
    data = []

    data.append(("V", '3'))
    data.append(("V", '"link_and_load"'))
    for obj in objects:
        data.append(("V", '"%s"' % obj))
    data.append(("V", '""'))

    # Call the main function
    data.append(("V", '"main"'))

    data = flush_data(address, data, username)
    v = urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "get_output", "username": username}))).read()
    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")
