"""
A module that allows users to run find and replace (e.g. 's/hello/goodbye/') scripts on previous messages (either their own or of another user).

Will only work in rooms/channels, as it becomes useless in a private message.

Currently supports IRC.
"""

import re

from aleph.utils.modules import Module
from aleph.modules.irc import Channel

#: IRC History module: Logs a message history
sed = Module(protocol='irc', requirements=['irc_history'])

@sed.regex("^(?:(.+): )?s/(.*)/(.*)/(g)?")
def find_and_replace (event, match):
	if not event.private:
		name, find, replace, global_replace = match.groups()
		
		# Name is not set if the user is correcting themself
		name, i = (name, 0) if name else (event.source.name, 1)
		
		# Search each line of the history under that name
		for line in Channel.get(event).history[name][i:]:
			if re.search(find, line):
				count = 0 if global_replace else 1
				replaced = re.sub(find, replace, line, count)
				return event.message_reply([
					"{source} thinks {name} meant to say: {replaced}",
					"{source} meant to say: {replaced}"
				][i].format(
					source	 = event.source.name,
					name     = name,
					replaced = replaced,
				))
		
		# Fail if nothing was found
		return event.message_reply("That didn't match anything.")
