#############################################################################
#
#	$Id: ES_NtService.py,v 1.1 2003/03/14 00:49:15 irmen Exp $
#	An NT service that runs the Pyro Event Service
#   Author: Syver Enstad  syver-en@online.no
#
#	This is part of "Pyro" - Python Remote Objects
#	Which is (c) Irmen de Jong - irmen@users.sourceforge.net
#
#############################################################################

import win32serviceutil
import threading
import win32service
from BasicNTService import BasicNTService

import sys
import Pyro
Pyro.config.PYRO_TRACELEVEL=3
from Pyro.EventService import Server
import sys


class PyroESThread(threading.Thread):
	""" The Pyro Event Service will run in this thread
	"""
	def __init__(self, args, stopcallback):
		threading.Thread.__init__(self)
		self._args = list(args)
		self._stopcallback = stopcallback
		
	def run(self):
		self.startPyroES()
		self._stopcallback()

	def startPyroES(self):
		""" ripped out of Pyro.EventService.Server and slightly changed to
		accomodate not using sys.argv, but self._args instead
		"""

		Args = Pyro.util.ArgParser()
		Args.parse(self._args,'hn:p:i:')
		if Args.hasOpt('h'):
			print 'Usage: es [-h] [-n hostname] [-p port] [-i identification]'
			print '  where -p = ES server port'
			print '        -n = non-default hostname to bind on'
			print '        -i = the required authentication ID for ES clients,'
			print '             also used to connect to other Pyro services'
			print '        -h = print this help'
			raise SystemExit
		host = Args.getOpt('n','')
		port = Args.getOpt('p',None)
		ident = Args.getOpt('i',None)
		if port:
			port=int(port)
		Args.printIgnored()
		if Args.args:
			print 'Ignored arguments:',' '.join(Args.args)

		print '*** Pyro Event Server ***'
		self.starter=Server.EventServiceStarter(identification=ident)
		self.starter.start(host,port)
	
	def shutdown(self):
		self.starter.running=0

	
class PyroES_NTService(BasicNTService):
	_svc_name_ = 'PyroES'
	_svc_display_name_ = "Pyro Event Service"
	_svc_description_ = "Provides event topics and publish/subscribe communication for Pyro"
	def __init__(self, args):
		super(PyroES_NTService, self).__init__(args)
		esargs = args
		self._esThread = PyroESThread(esargs, self.SvcStop)
		
	def _doRun(self):
		""" Overriden """
		self._esThread.start()

	def _doStop(self):
		""" Overridden """
		self._esThread.shutdown()
		self._esThread.join()

	def SvcStop(self):
		"""Overriden """
		super(PyroES_NTService, self).SvcStop()
		

if __name__ == '__main__':
	PyroES_NTService.HandleCommandLine()
