import urllib
import urllib2
import threading
import subprocess
import os

def local_print(string):
    print("\033[92m%s\033[0m" % string)

def remote_print(string):
    print("\033[94m%s\033[0m" % string)

def execute(scriptname, parameters=[], wait=False):
    if os.name == "nt":
        command = ["%s.bat" % scriptname] + parameters
    elif os.name == "posix":
        command = ["./%s.sh" % scriptname] + parameters
    else:
        raise Exception("Unknown OS: " + str(os.name))

    if wait:
        return subprocess.call(command, shell=False)
        return subprocess.call(command, shell=False, stdout=open('/tmp/output', 'w'), stderr=open('/tmp/output', 'w'))
    else:
        return subprocess.Popen(command, shell=False, stdout=open('/tmp/output', 'w'))

local_print("Welcome to the local shell!")
local_print("Please specify Modelverse location (default: localhost:8001)")

location = raw_input()
if location == "":
    address = "localhost"
    port = 8001
else:
    address, port = location.strip().split(":")

local_print("Username (default: test)")
username = raw_input()
if username == "":
    username = "test"
else:
    username = username.strip()

local_print("Switching context to Modelverse: all data is piped.")
local_print("To quit: execute command 'quit'")

def print_output():
    while 1:
        output = urllib2.urlopen(urllib2.Request("http://%s:%s/" % (address, port), urllib.urlencode({"op": "get_output", "username": username}))).read()
        l, r = output.split("&", 1)
        if "value" in l:
            output = l
        else:
            output = r
        _, output = output.split("=", 1)
        remote_print("%s" % str(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
    try:
        # Could be a number
        _ = float(command)
        command = str(command)
        local_print("Interpreting value as a number")
    except:
        if len(command) > 0 and command[0] == "\\":
            command = '{"value": "%s"}' % command[1:]
        else:
            command = '"%s"' % command
        local_print("Got command string: " + str(command))
    urllib2.urlopen(urllib2.Request("http://%s:%s/" % (address, port), urllib.urlencode({"op": "set_input", "element_type": "V", "value": command, "username": username}))).read()
