import sys
sys.path.append("wrappers")
from modelverse import *
import os
import json

import time
def json_service(port):
    def print_out_json(data):
        if isinstance(data, dict):
            # Serialize dictionary
            service_set(port, "D")
            service_set(port, len(data))
            for key, value in data.items():
                service_set(port, key)
                print_out_json(value)
        elif isinstance(data, list):
            # Serialize list
            service_set(port, "L")
            service_set(port, len(data))
            for value in data:
                print_out_json(value)
        elif data is None:
            service_set(port, "N")
        else:
            # Is a primitive value (normally), so send as-is
            service_set(port, "P")
            service_set(port, data)

    def fetch_data():
        data = service_get(port)
        if data == "D":
            rval = {}
            length = service_get(port)
            for _ in range(length):
                key = service_get(port)
                rval[key] = fetch_data()
        elif data == "L":
            rval = []
            length = service_get(port)
            for _ in range(length):
                rval.append(fetch_data())
        elif data == "P":
            rval = service_get(port)
        elif data == "N":
            rval = None
        else:
            raise Exception("Unknown data type: " + data)
        return rval

    start = time.time()

    mode = service_get(port)
    try:
        if mode == "decode":
            service_set(port, "OK")
            json_str = service_get(port)
            json_data = json.loads(json_str)
            print_out_json(json_data)

        elif mode == "encode":
            service_set(port, "OK")
            json_data = fetch_data()
            json_str = json.dumps(json_data)
            service_set(port, json_str)
            
        else:
            raise Exception("No such mode: " + mode)

    except Exception as e:
        service_set(port, str(e))
        raise

try:
    init(sys.argv[1])
    login("JSON", "JSON")

    service_register("JSON", json_service)

    try:
        if sys.version_info[0] < 3:
            while raw_input() != "STOP":
                pass
        else:
            while input() != "STOP":
                pass

    except EOFError:
        import time
        while 1:
            time.sleep(1.0)
    finally:
        service_stop()
except KeyboardInterrupt:
    pass
