""" Multiple modules for working with the IRC protocol. """

from collections import defaultdict

from aleph.utils.modules import Module

settings = {'protocol': 'irc'}

#: IRC module: Stores basic data on irc events, such as channel users and topics
irc = Module(**settings)

class Channel (object):
	@staticmethod
	def get (event):
		""" Fetch a channel object for an event """
		return event.handler.channels[event.channel]
	
	@staticmethod
	def remove (event):
		""" Delete channel object for an event """
		del event.handler.channels[event.channel]
	
	def __init__ (self):
		self.topic = None
		self.names = list()

@irc.listener
def connect (handler):
	""" Creates the attributes ``data`` and ``channels`` on the handler object. """
	handler.data = defaultdict(lambda: None)
	handler.channels = defaultdict(Channel)
	
@irc.listener
def join (event):
	Channel.get(event).names.append(event.source.name)

@irc.listener
def part (event):
	# Remove the channel if Aleph is parting the channel
	if event.source.name == event.handler.config['nick']:
		del event.handler.channels[event.channel]
	else:
		Channel.get(event).remove(event.source.name)
	
@irc.listener
def topic (event):
	Channel.get(event).topic = event.topic

@irc.listener
def names (event):
	Channel.get(event).names = event.names

@irc.listener
def motd (event):
	event.handler.data['motd'] = event.motd

#: IRC Commands Module: basic commands for controling an Aleph irc handler
irc_commands = Module(requirements=['irc'], **settings)

@irc_commands.command
def say (event, text):
	channel, text = text.split(' ', 1)
	event.handler.privmsg(channel, text)

@irc_commands.command
def join (event, text):
	for channel in text.split(' '):
		event.handler.join(channel)

@irc_commands.command
def part (event, text):
	for channel in text.split(' '):
		event.handler.part(channel)

@irc_commands.command
def quit (event, text):
	event.handler.quit(text)

#: IRC History module: Logs a message history
irc_history = Module(**settings)
irc_history.requirements = ['irc']

@irc_history.listener
def join (event):
	if event.isme():
		Channel.get(event).history = defaultdict(list)

@irc_history.listener
def part (event):
	if event.isme():
		Channel.remove(event)

@irc_history.listener
def message (event):
	if not event.private:
		history = Channel.get(event).history[event.source.name]
		history.insert(0, event.message_text())
		history = history[:event.handler.config.get('scrollback_limit', 10)]
