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

use Irssi qw();
$VERSION = '0.0.1';
%IRSSI = (
	authors     => 'Patrick Haller',
	contact     => 'patrick.haller.ws',
	name        => 'rotate',
	description => 'Rotate to next channel because of /j #chan<TAB> bug',
	url         => 'http://haller.ws/projects/irssi/rotate',
	license     => 'GNU General Public License',
	changed     => '$Date: 2007-01-13 12:00:00 +0100 (Sat, 13 Jan 2007) $'
);

sub in($@) {
	my ($element, @array) = @_;
	for my $i (0 .. scalar @array) {
		$array[$i] eq $element and return $i;
	}
	return;
}

sub rotate_channel {
	my ($channel_name) = @_;
	my @channels = Irssi::channels();
	my @names = map { $_->{name} } @channels;
	#print join ' ', "  available channels: ", @names;
	my $index = in $channel_name, @names;
	my $channel = $channels[ ($index + 1) % scalar @channels ];
	#print "  switching to channel ", $channel->{name};
	return $channel->{name};
}

sub rotate_cmd {
	my ($data, $server, $window) = @_;
	require 'Data/Dumper.pm';
	$window->{type} ne 'CHANNEL' and do {
		print "no can do: didn't get a CHANNEL type, got: ", Data::Dumper::Dumper $window;
		return;
	};
	#print "  currently in ", $window->{name};
	my $cmd = sprintf("join %s", (rotate_channel $window->{name}));
	Irssi::command($cmd);
}


Irssi::command_bind r => \&rotate_cmd;
