use Irssi;
$VERSION = "1.0";
%IRSSI = (
    authors     => 'David Leadbeater',
    contact     => 'dgl@dgl.cx',
    name        => 'conncount',
    description => 'Counts connections and shows them as a statusbar item (for opers)',
    license     => 'GNU GPLv2 or later',
    url         => 'http://irssi.dgl.cx/',
);

# Usage: /statusbar window add conncount
# You'll also need to do /set opermode +c

use strict;
use Irssi::TextUI;

my %tags = ( );

# Called to make the status bar item
sub conncount {
  my ($item, $get_size_only) = @_;
  my $server = Irssi::active_server;

  if(not ref $server or not $server->{server_operator}) {
    return unless ref $item;
    $item->{min_size} = $item->{max_size} = 0;
    return;
  }

  my $sb = "{sb $tags{$server->{tag}}}";

  $item->default_handler($get_size_only, $sb, undef, 1);
}

sub notice {
   my($server, $msg, $sender, $address, $target) = @_;

   return if $address or $sender !~ /\./;

   if($msg =~ /\*\*\* Notice -- Client (connecting|exiting): /) {
      if(exists $tags{ $server->{tag} }) {
         $tags{ $server->{tag} } += ($1 eq "connecting" ? +1 : -1);
         Irssi::statusbar_items_redraw('conncount');
      }else{
         $server->command("lusers");
      }

      if(Irssi::settings_get_bool('conncount_hide_connects')) {
         Irssi::signal_stop;
      }
   }
}

sub luser {
   my($server, $data) = @_;
   $tags{ $server->{tag} } = $1 if $data =~ /(\d+)/;
   Irssi::statusbar_items_redraw('conncount');
}

Irssi::settings_add_bool('conncount', 'conncount_hide_connects', 1);

Irssi::statusbar_item_register('conncount', undef, 'conncount');

Irssi::signal_add('message irc notice', 'notice');
Irssi::signal_add('event 255', 'luser');

