import urllib
import urllib2
import threading
import subprocess
import os
import sys
import json

sys.path.append("../interface/HUTN")
sys.path.append("interface/HUTN")
from hutn_compiler.compiler import main as hutn_compile

memory = {}

def send_data(commands, address, taskname):
    urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "set_input", "data": json.dumps(commands), "taskname": taskname}))).read()

def local_print(string):
    if os.name == "posix":
        # Nicer colour output when using posix (and thus supporting colour)
        string = "\033[92m%s\033[0m" % string
    print(string)

def remote_print(string):
    if os.name == "posix":
        # Nicer colour output when using posix (and thus supporting colour)
        string = "\033[94m%s\033[0m" % string
    print(string)

local_print("Welcome to the local shell!")
try:
    address = sys.argv[1]
except IndexError:
    address = "http://127.0.0.1:8001"
try:
    taskname = sys.argv[2]
except IndexError:
    import random
    taskname = str(random.random())

# If task doesn't exist yet, we create it
urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "set_input", "value": '"%s"' % taskname, "taskname": "task_manager"}))).read()

local_print("Switching context to Modelverse: all data is piped.")
local_print("Use command $ to switch to HUTN parsing mode.")
local_print("Use \\ before the value to use a primitive value different from a string, which is already JSON serialized.")
local_print("To quit: execute command 'quit'")

def print_output():
    while 1:
        output = urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "get_output", "taskname": taskname}))).read()
        remote_print("%s" % str(json.loads(output)))

thrd = threading.Thread(target=print_output)
thrd.daemon = True
thrd.start()

while 1:
    command = raw_input()
    if command == "quit":
        local_print("Received quit: breaking connection to Modelverse immediately!")
        break

    if command.startswith("$"):
        # Invoke the HUTN parser
        tmp_file = "__action.alc"
        with open(tmp_file, 'w') as f:
            f.write("")
        local_print("Entering HUTN coding environment.")
        local_print("There is no nice editor right now, so please just modify the file '__action.alc' in this folder.")
        while 1:
            local_print("When you are done, press <return> to continue.")
            raw_input()
            local_print("File contents:")
            with open(tmp_file, 'r') as f:
                local_print(f.read())
            local_print("Sending file through parser!")

            try:
                commands = hutn_compile(tmp_file, "interface/HUTN/grammars/actionlanguage.g", "CS")
                local_print("Compilation succesfully terminated!")
                local_print("Upload this file? [Y/n]")
                i = raw_input()
                if i == "n\n":
                    continue
                send_data(commands, address)
            except:
                import traceback
                traceback.print_exc()
                local_print("Error during compilation!")
                local_print("Do you want to try again? [Y/n]")
                i = raw_input()
                if i[0] == "n":
                    break

            local_print("HUTN input finished, going back to regular prompt!")
    else:
        # Just send a normal request
        if command.startswith("\\"):
            command = command[1:]
        else:
            command = '"%s"' % command

        urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "set_input", "value": command, "taskname": taskname}))).read()
