## cwho.pl - cached /WHO
## fahren@bochnia.pl

## Usage: /CWHO [-a | -l | -o | -v ] [ mask ]

Irssi::theme_register([
	'cwho_line', '%K[%W$[!-3]0%K][%C$[1]1%B$[9]2%K][%B$[-10]3%P@%B$[34]4%K]%n'
]);

sub cmd_cwho {
	my ($pars, $server, $winit) = @_;
	my @data = split(/ /, $pars);
	my ($cmode, $cmask, $i) = ("", "*!*@*", 0);

	if ($winit && $winit->{type} ne "CHANNEL") {
	    Irssi::print("You don't have active channel in that window");
	    return;
	}

	my $channel = $winit->{name};
	
	while ($_ = shift(@data)) {
		/^-a$/ and $cmode = "", next;
		/^-l$/ and $cmode = "X", next;
		/^-o$/ and $cmode = "@", next;
		/^-v$/ and $cmode = "v", next;
		/[!@.]+/ and $cmask = $_, next;
	}
	
	for my $hash ($winit->nicks()) {
		my $mode = ($hash->{op})? "@" : ($hash->{voice})? "v" : "";
		if ($cmode eq "X") {
			next if $hash->{op};
		} elsif (!($mode =~ /$cmode/)) {next}
		
		next unless $server->mask_match_address($cmask, $hash->{nick}, $hash->{host});	
		my ($user, $host) = split(/@/, $hash->{host});
		
		$server->printformat($channel, MSGLEVEL_CLIENTCRAP, 'cwho_line',
					++$i, $mode, $hash->{nick}, $user, $host);
	}

	Irssi::print("No matches for \'$cmask\'.") unless $i;
}

Irssi::command_bind("cwho", "cmd_cwho");

