""" A python irc library, using the reactor pattern. """

__version__ = '4.0'

""" Aleph - A python IRC library """

import imp, argparse, logging.config

from aleph.dispatch import Dispatcher
from aleph.reactor import Reactor
from aleph.utils.log import getlog, defaults

class Aleph (object):
	"""	Sets up and manages the configuration of the reactor. """

	def __init__ (self, config):
		# Setup logging
		self.log = getlog(self)
		self.log.info("Initialising")
		
		#: The top-level configuration dictionary
		self.config = config
		
		# The dispatcher recives the events generated by the reactor
		self.dispatcher = Dispatcher(self.config['modules'])
		self.reactor = Reactor(self.config, self.config.pop('connections'))
	
	def start (self):
		"""	Tick until stopped """
		self.reactor.set_callback(self.dispatcher)
		self.reactor.loop()

def run ():
	""" Run aleph from the command line """
	
	parser = argparse.ArgumentParser(
		description="Load and run an Aleph configuration module.",
		epilog="Further documentation can be found here:"
		"\nhttp://aleph.readthedocs.org/en/latest/")

	parser.add_argument('-v', '--version', action='version',
		version='Aleph %s' % __version__)
		
	parser.add_argument('--nostart', action='store_true',
		help='do not start Aleph')
		
	parser.add_argument('--level', type=str, default='INFO',
		help='the logging level to use')
		
	parser.add_argument('config', type=str,
		help='the configuration module to load')
	
	args = parser.parse_args()
	
	config = imp.load_source('aleph.config', args.config).config
	
	# Setup logging before Aleph is initialised,
	# using the level argument given in the arguments
	lconfig = config.get('logging', defaults)
	lconfig['loggers']['']['level'] = args.level
	logging.config.dictConfig(lconfig)
	
	# Initialise Aleph
	aleph = Aleph(config)
	
	# Run Aleph (unless requested)
	if not args.nostart:
		aleph.start()
