#!/opt/local/bin/python
import json
import urllib
import urllib2
import sys
from compiler import main


input_file = '../test/acceptance/mirror.al'
mode = "CS"
test_input = 1
test_output = "1"


user = 'test'
timeout = 10
grammar_file = '../grammars/actionlanguage.g'


if mode == "CS":
    interface = 1
elif mode == "PS":
    interface = 0
else:
    raise RuntimeError("Mode be either PS or CS")


def set_input(value, user=user, timeout=timeout):
    if type(value) in (list, tuple):
        args = {"op": "set_input",
                "data": json.dumps(value),
                "username": user}
    else:
        args = {"op": "set_input",
                "element_type": "V",
                "value": value,
                "username": user}
    urllib2.urlopen(
        urllib2.Request("http://localhost:8001/", urllib.urlencode(args)),
        timeout=timeout).read()


def get_output(user=user, timeout=timeout):
    return urllib2.urlopen(
        urllib2.Request("http://localhost:8001/",
                        urllib.urlencode({"op": "get_output",
                                          "username": user})),
        timeout=timeout).read()


# create user
set_input('"{}"'.format(user), "user_manager")

# set interface
set_input(interface)

# compile to code
code = main(input_file, grammar_file, mode)

# send code
if mode == "CS":
    var_list = {}
    data = []
    for p in code:
        if isinstance(p, int):
            if p not in var_list:
                set_input(data)
                data = []
                val = get_output()
                val = val.split("=", 2)[1].split("&", 1)[0]
                var_list[p] = val
                continue
            else:
                val = var_list[p]
                t = "R"
        else:
            val = p
            t = "V"
        data.append([t, val])
    set_input(data)
elif mode == "PS":
    set_input(json.dumps(code))

# send input (may be a list or a single value)
set_input(test_input)

# get output
val = get_output()
val = val.split("=", 2)[2]
# print("For input %s, got output %s, instead of %s" % (test_input, val,
#                                                       test_output))
assert val == test_output
print val == test_output
