#!/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 traceback

from winswitch.util.main_loop import loop_init
reactor = loop_init(False)

# Our imports
from winswitch.client.client_base import ClientBase
from winswitch.util.simple_logger import Logger


class WinSwitchClient(ClientBase):
	"""
	This client does not interact with the user.
	All the messages are just printed on screen and the questions addressed to the user
	raised by other parts of the code will not be answered.
	"""

	def notify(self, title, message, delay=None, callback=None, notification_type=None, from_server=None, from_uuid=None):
		self.slog(None, title, message, type)

	def server_message(self, *args):
		self.slog(None, *args)

	def ask(self, title, text, nok_callback, ok_callback, password=False, buttons=None, icon=None, UUID=None):
		self.serror("not implemented!", title, text, nok_callback, ok_callback, password, buttons, icon, UUID)

	def cancel_ask(self, UUID):
		self.serror("not implemented!", UUID)

	def __init__(self, reactor, reactor_run, reactor_stop):
		ClientBase.__init__(self, reactor, reactor_run, reactor_stop)


reactor_lock = False
def do_reactor_run(logger):
	global reactor_lock
	if reactor_lock:
		logger.debug("() already running!")
		#return
	logger.log()
	import twisted.internet.reactor as twisted_reactor
	reactor = twisted_reactor
	try:
		reactor_lock = True
		reactor.run(installSignalHandlers=0)
	except Exception, e:
		reactor_lock = False
		logger.exc(e)
		raise e

def do_reactor_stop(logger):
	logger.log()
	import twisted.internet.reactor as twisted_reactor
	import twisted.internet.error
	reactor = twisted_reactor
	try:
		reactor.callFromThread(reactor.stop)
	except twisted.internet.error.ReactorNotRunning, e:
		logger.error("() %s" % e)
	except Exception, e:
		logger.exc(e)


def main():
	client = None
	logger = None
	try:
		logger = Logger("client")
		import twisted.internet.reactor as twisted_reactor
		client = WinSwitchClient(twisted_reactor, lambda : do_reactor_run(logger), lambda : do_reactor_stop(logger))
	except Exception, e:
		if logger:
			logger.error("main()", e)
		else:
			print("Error importing our classes..")
			traceback.print_exc()
		sys.exit(1)

	exit_code = 0
	try:
		client.run()
	except Exception, e:
		logger.error("main() caught exception, closing client", e)
		try:
			client.cleanup()
		except Exception, e:
			logger.error("main() ouch! exception during cleanup()", e)
		exit_code = 1
	logger.log("main() exit code=%d, waiting for all other threads to exit - this may take a few seconds" % exit_code)
	return	exit_code

if __name__ == "__main__":
	main(sys.argv)
