#!/usr/bin/env python

# This file is part of Window-Switch.
# Copyright (c) 2009-2013 Antoine Martin <antoine@nagafix.co.uk>
# Window-Switch is released under the terms of the GNU GPL v3

import sys
import time
import os

#disable logging so all we get is the port:
from winswitch.util.simple_logger import Logger, set_log_to_file, set_log_to_tty
from winswitch.util.server_portinfo import get_local_servers_portinfo

logger=Logger("server_portinfo_monitor", log_colour=Logger.CYAN)

QUERY="query"
EXIT="exit"

def send_portinfo(start):
	port_info = get_local_servers_portinfo()
	if len(port_info)>0:
		for pi in port_info:
			(host, port, ID) = pi		#ignore ID
			sys.stdout.write("%s:%s %s\n" % (host, port, ID))
	else:
		if start:
			import subprocess
			cmd = ["winswitch_server", "-d"]
			devnull = file(os.devnull, 'w')
			subprocess.Popen(cmd, shell=True, stdin=devnull, stdout=devnull, stderr=devnull)
			#start = False #just do it once?
		sys.stdout.write("\n")
	sys.stdout.flush()
	time.sleep(1)
	ask = sys.stdin.readline().rstrip()
	if ask == EXIT:
		sys.exit()
	if ask != QUERY:
		time.sleep(5)

def main():
	set_log_to_file(False)
	set_log_to_tty(False)

	start = False
	args = sys.argv[:]
	if "--start" in args:
		args.remove("--start")
		start = True

	#add key if provided on command line, add it
	if len(args)==2:
		from winswitch.util.add_key import do_add_winswitch_client
		key = args[1]
		do_add_winswitch_client(key)

	while True:
		try:
			send_portinfo(start)
		except KeyboardInterrupt:
			return

if __name__ == "__main__":
	main()
