COMPILER_PATH = "interface/HUTN"

import sys
sys.path.append(COMPILER_PATH)
sys.path.append("wrappers")
from hutn_compiler.compiler import main as do_compile
from modelverse import *
import os

import time

def clean_code(code):
    if code == "":
        return code

    code_fragments = code.split("\n")
    code_fragments = [i.rstrip() for i in code_fragments if i.strip() != ""]
    code_fragments = [i.replace("    ", "\t") for i in code_fragments]
    initial_tabs = min([len(i) - len(i.lstrip("\t")) for i in code_fragments])
    code_fragments = [i[initial_tabs:] for i in code_fragments]
    code_fragments.append("")
    code = "\n".join(code_fragments)
    return code.encode('ascii', 'replace')

def compile_service(port):
    start = time.time()
    temp_file = ".tmp_%s" % port

    def compile_AL(code):
        code = clean_code(code)

        if code == "":
            return [0]

        with open(temp_file, "w") as f:
            f.write(code.decode())
            f.flush()

        compiled = do_compile(temp_file, COMPILER_PATH + "/grammars/actionlanguage.g", "CS")
        os.remove(temp_file)
        return compiled

    def compile_model(code):
        code = clean_code(code)

        if code == "":
            return [0]

        with open(temp_file, "w") as f:
            f.write(code.decode())
            f.flush()

        compiled = do_compile(temp_file, COMPILER_PATH + "/grammars/modelling.g", "M")
        os.remove(temp_file)
        return compiled

    mode = service_get(port)
    code = service_get(port)

    try:
        if mode == "code":
            compiled = compile_AL(code)
            service_set(port, "OK")
            service_set(port, compiled)
        elif mode == "model":
            compiled = compile_model(code)
            service_set(port, "OK")
            service_set(port, compiled)
        else:
            raise Exception("No such mode: " + mode)
    except Exception as e:
        service_set(port, str(e))
        raise

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

    service_register("compiler", compile_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
