use Irssi;
use strict;
use vars qw($VERSION %IRSSI @bandwidth);

$VERSION = '1.00';
%IRSSI = (
    authors 	=> 'Eric Jansen',
    contact 	=> 'chaos@sorcery.net',
    name 	=> 'bandwidth',
    description => 'Displays the top 15 of bandwidth consuming users',
    license 	=> 'GPL',
    modules	=> '',
    url		=> 'http://xyrion.org/irssi/',
    changed 	=> 'Sun Mar  2 16:27:36 CET 2003'
);

sub cmd_bandwidth {

    my ($data, $server, $witem) = @_;

    $server->redirect_event('stats l', 1, undef, 0, undef,
	{
	    'event 211' => 'redir statsl_line',
	    'event 219' => 'redir statsl_done'
	}
    );
    $server->send_raw("STATS L *");
}

sub event_statsl_line {

    my ($server, $data, $from, $address) = @_;

    if($data =~ /([^\s]+) ([^\s]+)\[\@([^\]]+)\] \d+ \d+ (\d+) \d+ (\d+) (\d+) :\d+$/) {

	my($target, $nick, $host, $sent, $recv, $time) = ($1, $2, $3, $4, $5, $6);

	push @bandwidth, {
	    'nick' => $nick,
	    'host' => $host,
	    'recv' => int 1024*$recv/$time,
	    'sent' => int 1024*$sent/$time
	} unless $nick =~ /\./;
    }
}

sub event_statsl_done {

    my ($server, $data, $target, $address) = @_;

    display_top($server, $target, 'sent', 15);
    display_top($server, $target, 'recv', 15);

    undef @bandwidth;
}

sub display_top {

    my ($server, $target, $sort, $num) = @_;

    my @top = sort {$b->{$sort} <=> $a->{$sort}} @bandwidth;

    $server->printformat($target, MSGLEVEL_CRAP, 'bandwidth_head');

    $num = $num >= $#top+1 ? $#top : $num - 1;
    for my $i (0..$num) {

	$server->printformat($target, MSGLEVEL_CRAP, 'bandwidth_line', $i+1, $top[$i]->{'nick'}, $top[$i]->{'sent'}, $top[$i]->{'recv'}, $top[$i]->{'host'});
    }

}

Irssi::command_bind('bandwidth', 'cmd_bandwidth');
Irssi::signal_add('redir statsl_line', 'event_statsl_line');
Irssi::signal_add('redir statsl_done', 'event_statsl_done');
Irssi::Irc::Server::redirect_register('stats l', 0, 0,
    {
	'event 211' => -1
    },
    {
	'event 219' => -1
    },
    undef
);
Irssi::theme_register([
    'bandwidth_head', '{hilight      Nick                    Sending      Receiving  IP/port}',
    'bandwidth_line', '[$[-2]0] {nick $[17]1} [$[-8]2 B/s] [$[-8]3 B/s] {host $4}'
]);
