#!/usr/bin/env python

import sys
import os.path

args = sys.argv
verbose = False
for x in ["-v",  "--verbose"]:
	if x in args:
		verbose = True
		args.remove(x)
from winswitch.util.simple_logger import set_log_to_tty
set_log_to_tty(verbose)

from winswitch.net.local_socket_client import get_responses
from winswitch.net.local_common import COMMAND_LIST_SERVERS, COMMAND_LIST_ALL_SERVERS, COMMAND_EXIT
from winswitch.util.format_util import parse_message_string

cmds = {COMMAND_LIST_SERVERS : "List the servers currently connected or previously connected",
		COMMAND_LIST_ALL_SERVERS : "List all the servers",
		COMMAND_EXIT : "Make the client terminate" }

def usage():
	print("Usage: %s" % os.path.basename(args[0]))
	print("")
	def argi(arg, info):
		print("     %s %s" % (arg.ljust(30), info))
	argi("-h, --help", "This information")
	argi("-v, --verbose", "Turn on verbose logging")
	for cmd,descr in cmds.items():
		argi(cmd, descr)
	print("")
	return 1


def main():
	global args
	if len(args)!=2:
		return usage()
	cmd = args[1]
	if cmd not in cmds.keys():
		return usage()

	r = get_responses([cmd])
	parsed = []
	for x in r:
		(cmd, args) = parse_message_string(x)
		if cmd!="OK":
			print("server error: %s" % x)
			return 1
		parsed.append(args)
	#for each response:
	for x in parsed:
		for v in x:
			print(v)
	return 0


if __name__ == "__main__":
	e=main()
	sys.exit(e)
