""" Functions to parse and format IRC messages. """

from data import Hostmask

def parse_line (string):
	"""	Parse an IRC message in the form ``[:<source> ]<command>[ <parameters>][ :<trailing>]`` """
	
	split = lambda string: string.split(' ',1)
	get_token = lambda string: split(string) if len(split(string)) > 1 else (split(string)[0], None)
	
	# Default variables for parameters and trailing,
	# as it is possible neither will be assigned
	parameters, trailing = [], None
	
	# Remove the source from the message if it has one
	if string[0] == ':':
		source, string = get_token(string[1:])
		source = Hostmask(source)
	
	# Get the command from the string
	command, string = get_token(string)
	
	# While there are still elements in the string to parse,
	# get either the trailing element or another parameter
	while string:
		if string[0] == ':':
			trailing = string[1:].strip()
			break
		else:
			param, string = get_token(string)
			parameters.append(param)
	
	# Return the message as a dictionary
	return {'source':source, 'command':command, 'parameters':parameters, 'trailing':trailing}

def format_line (command, parameters = [], trailing = None):
	"""	Format an outgoing IRC message from the given variables """
	message = "{command} {parameters} :{trailing}" if trailing else "{command} {parameters}"
	return message.format(command=command, parameters=' '.join(parameters), trailing=trailing)
