use strict;

use Irssi::TextUI;
use Irssi 20020101.0250 ();

use vars qw ($VERSION %IRSSI);

$VERSION = "0.1";
%IRSSI = (
    authors     => 'Sascha Schneider, Petr Baudis',
    contact     => 'Sascha@Linux-Administration.de, pasky@ji.cz',
    name        => 'opregain',
    description => 'Cycles the channel to regain op, while preserving old topic.',
    license     => 'GNU GPLv2 or later',
    url         => 'http://pasky.ji.cz/~pasky/dev/irssi/',
);

# FIXME: we'll probably get confused when we'll have to cycle more chans at once
my $timeout_tag_1 = 0;
my $timeout_tag_2 = 0;

sub check_server_channel() {
	my ($server, $channel) = @_;

	return check_channel($server->channel_find($channel));
}

sub check_channel() {
	my ($channel) = @_;
	
	return unless Irssi::settings_get_bool('activate_opregain');

	Irssi::print "=> @_";
	
	Irssi::timeout_remove($timeout_tag_1) if ($timeout_tag_1);
	$timeout_tag_1 = Irssi::timeout_add(200, 'check_channel_do', $channel)
}

sub check_channel_do() {
	my ($channel) = @_;
	my ($ops, $total) = (0, 0);

	Irssi::timeout_remove($timeout_tag_1);
	$timeout_tag_1 = 0;

	for ($channel->nicks()) {
		$total++;
		last if ($total > 1);
		
		if ($_->{op}) {
			$ops++;
			last;
		}
	}

	Irssi::print("total -> ($total, $ops)");

	Irssi::timeout_remove($timeout_tag_2) if ($timeout_tag_2);
	$timeout_tag_2 = Irssi::timeout_add(5000, 'cycle_channel', $channel)
		if (($total eq 1) && ($ops eq 0));
}

sub cycle_channel() {
	my ($channel) = @_;
	my $server = $channel->{server};
	my $chan_name = $channel->{name};

	Irssi::print("ch -> $chan_name");

	Irssi::timeout_remove($timeout_tag_2);
	$timeout_tag_2 = 0;

	my $topic = $channel->{topic};
	$server->command("/CYCLE $chan_name");
	$server->command("/topic $chan_name $topic") if ($topic);
}

Irssi::settings_add_bool('misc', 'activate_opregain', 1);

Irssi::signal_add_last('channel mode changed', 'check_channel');
Irssi::signal_add_last('nick mode changed', 'check_channel');

Irssi::signal_add_last('message part', 'check_server_channel');
Irssi::signal_add_last('message quit', 'check_server_channel');
Irssi::signal_add_last('message kick', 'check_server_channel');

