from Client import Client
from Log import log

from sims4.commands import *

COMMAND_SERVER_PORT	= 8008

_commandClient = None

class Output:
	def __init__(self,connection):
		self._cheatOutput = CheatOutput(connection)
		
	def __call__(self,line):
		log(line)
		
		self._cheatOutput(line)

@Command("rtbp.command",command_type = CommandType.Live)
def rtbpCommand(command = None,_connection = None):
	out = Output(_connection)
	
	out("Command: {}".format(command))
	
	global _commandClient
	
	if _commandClient==None:
		try:
			_commandClient = Client("127.0.0.1",COMMAND_SERVER_PORT)
			
		except Exception as error:
			_commandClient = None
			
			out("Unable to send command: cannot connect to RTBP's command server: {}\nPlease try again in a couple minutes.".format(error))
			
			return
	
	_commandClient.sendString(command+"\n")
	
	while True:
		reply = _commandClient.read()
		
		if reply==b"EOF\n":
			break
		
		out(str(reply,"ascii"))
