# EmptyRejoin - Automatically rejoin channel when you're alone there and
# opless.
#
# Partially based on usercount.pl by David Leadbeater <dgl@dgl.cx>.
#
# $Id: map.pl,v 1.2 2002/02/01 22:21:20 pasky Exp pasky $


use Irssi;
use Irssi::Irc;

use strict;

use vars qw ($VERSION %IRSSI $rcsid);

$rcsid = '$Id: map.pl,v 1.2 2002/02/01 22:21:20 pasky Exp pasky $';
($VERSION) = '$Revision: 1.2 $' =~ / (\d+\.\d+) /;
%IRSSI = (
          name        => 'emptyrejoin',
          authors     => 'Petr Baudis',
          contact     => 'pasky@ji.cz',
          url         => 'http://pasky.ji.cz/~pasky/dev/irssi/',
          license     => 'GPLv2, not later',
          description => 'Cycle opless channel automatically, if you are alone there.'
         );

my $timeout_tag = 0;

sub refresh {
   if ($timeout_tag > 0) {
      Irssi::timeout_remove($timeout_tag);
      $timeout_tag = 0;
   }






  my $channel = shift;
  my $server = $channel->{server};

  $ops = $halfops = $voices = $normal = 0;
  for ($channel->nicks()) {
    if ($_->{op}) {
      $ops++;
    } elsif ($_->{halfop}) {
      $halfops++;
    } elsif ($_->{voice}) {
      $voices++;
    } else {
      $normal++;
    }
  }

  $total = $ops+$halfops+$voices+$normal;
  if (!Irssi::settings_get_bool('usercount_show_zero')) {
    $ops = undef if ($ops == 0);
    $halfops = undef if ($halfops == 0);
    $voices = undef if ($voices == 0);
    $normal = undef if ($normal == 0);
  }

}

sub refresh_check {
   my $channel = shift;

   # don't refresh immediately, or we'll end up refreshing 
   # a lot around netsplits
   Irssi::timeout_remove($timeout_tag) if ($timeout_tag > 0);
   $timeout_tag = Irssi::timeout_add(500, 'refresh', undef);
}

Irssi::signal_add_last('nicklist new', 'refresh_check');
Irssi::signal_add_last('nicklist remove', 'refresh_check');

Irssi::print("EmptyRejoin $VERSION loaded...");
