## relm.pl/Irssi/fahren@bochnia.pl

## Usage: /RELM [-l || index] [target]
## ex. /RELM -l
## to list last 15 messages;
## /RELM 4,7-10,13
## to redirect msg #4, 7, 8, 9, 10, 13 to current channel/query;
## /RELM
## to redirect last message to current channel/query;

use Irssi;

sub cmd_relm {
	my ($args, $server, $winit) = @_;
	my $ircnet = lc($server->{tag});
	my ($which, $where) = split(/ /, $args, 2);
	
	$where = $which unless $which =~ /[0-9]/;

	unless ($which) {
		$which = scalar(@{$relm{lc($ircnet)}});
	}

	unless (@relm{$ircnet}) {
		Irssi::print("%R>>%n Nothing in relm buffer.", MSGLEVEL_CRAP);
		return;
	}

	if ($where eq "-l") {
		Irssi::print(">> ---- Context ------------------------", MSGLEVEL_CRAP);
		for (my $i = 0; $i < scalar(@{$relm{$ircnet}}); $i++) {
			$numspace = sprintf("%.2d", $i+1);
			Irssi::print("[%W$numspace%n] $relm{$ircnet}[$i]", MSGLEVEL_CRAP);
		}
		return;
	}

	unless ($where) {
		if ($winit && $winit->{type} ne "CHANNEL" && $winit->{type} ne "QUERY") {
			Irssi::print("%R>>%n You have to join channel first", MSGLEVEL_CRAP);
			return;
		}
		$where = $winit->{name};
	}
	
	$which =~ s/,/ /g;
	my @nums;
	for my $num (split(/ /, $which)) {
		if ($num =~ /-/) {
			my ($start, $end) = $num =~ /([0-9]+)-([0-9]*)/;
			for (;$start <= $end; $start++) {
				push(@nums, $start - 1);
			}
		} else {
			push(@nums, $num - 1);
		}
	}
	
	for my $num (@nums) {
		unless ($relm{$ircnet}[$num]) {
			Irssi::print("%R>>%n No such message in relm buffer /" . ($num + 1). "/", MSGLEVEL_CRAP);
		} else {
			Irssi::active_server()->command("msg $where $relm{$ircnet}[$num]");
		}
	}
}

sub event_privmsg {
	my ($server, $data, $nick, $address) = @_;
	my ($target, $text) = split(/ :/, $data, 2);
	my $ircnet = lc($server->{tag});

	return if ($server->{nick} ne $target);
	my $relm = "\cv[$nick!$address]\cv $text";
	splice(@{$relm{$ircnet}}, 0, 1) if scalar(@{$relm{$ircnet}}) > 14;
	push(@{$relm{$ircnet}}, $relm);
}

Irssi::command_bind("relm", "cmd_relm");
Irssi::signal_add("event privmsg", "event_privmsg");


