#!/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 twisted.internet import reactor, protocol
from twisted.protocols import basic

# Our imports
from winswitch.util.file_io import get_local_server_socket
from winswitch.util.common import visible_command
from winswitch.util.simple_logger import Logger
from winswitch.consts import DELIMITER

TIMEOUT = 5

class LocalServerMessenger:
	def __init__(self, messages):
		Logger(self)
		server_socket = get_local_server_socket()
		factory = LocalServerSocketFactory(self.stop, messages)
		self.reactor = reactor
		self.reactor.connectUNIX(server_socket, factory, timeout=TIMEOUT)

	def start(self, handle_signals=True):
		self.log()
		# start listening
		self.reactor.run(installSignalHandlers=handle_signals)

	def stop(self):
		self.reactor.stop()


class LocalServerSocketChannel(basic.LineReceiver):
	def __init__ (self):
		Logger(self)
		self.debug()
		self.delimiter = DELIMITER

	def disconnect(self):
		self.debug()
		self.factory.closing = True
		self.transport.loseConnection()

	def connectionMade(self):
		self.log()
		for message in self.factory.messages:
			self.sendLine(message)
		self.disconnect()

	def connectionLost(self, reason):
		self.log()

	def lineReceived(self, line):
		self.debug("(%s)" % visible_command(line))
		#do nothing... (sender only)


class LocalServerSocketFactory(protocol.ClientFactory):
	# the class of the protocol to build when new connection is made
	protocol = LocalServerSocketChannel

	def __init__ (self, stop, messages):
		Logger(self)
		self.debug()
		self.closing = False
		self.messages = messages
		self.stop = stop

	def clientConnectionLost(self, connector, reason):
		if self.closing:
			self.debug("(%s,%s)" % (str(connector), reason))
		else:
			self.error("(%s,%s)" % (str(connector), reason))
		self.stop()

	def clientConnectionFailed(self, connector, reason):
		self.error("(%s,%s)" % (str(connector), reason))
		self.stop()




def main():
	from twisted.python import threadable
	threadable.init(1)
	messages = sys.argv[1:]
	try:
		messenger = LocalServerMessenger(messages)
		messenger.start()
	except:
		print("local_server_messenger.main() exception")
		traceback.print_exc(file=sys.stdout)
		sys.exit(1)
		if messenger:
			messenger.stop()


if __name__ == "__main__":
	main()
