#!/usr/bin/perl
#use strict;
use Irssi;
use Irssi::Irc;

$VERSION = 20030909;
%IRSSI = (
	authors => 'Michał Mirosław',
	contact => 'mirqus@lagoon.freebsd.lublin.pl',
	name    => 'topic',
	description => 'Topic manipulation aid',
	license => 'GNU GPL v2',
	url     => undef,
	changed => '2003/09/09'
);

Irssi::theme_register([
	'last_topic' => 'Last topic was (by {hilight $1}): $3',
	'no_chan' => 'Channel {hilight $0} not found'
]);

my %last_topic;
my %last_topic_by;

sub sig_topic
{
	my ($chn) = @_;

	my $chn_tag = $chn->{server}->{tag} . "/" . $chn->{name};
	if (exists $last_topic{$chn_tag}) {
		my ($bynick, $byuh) = split('!', $last_topic_by{$chn_tag});
		$chn->printformat(MSGLEVEL_TOPICS|MSGLEVEL_NO_ACT, 'last_topic',
			$chn->{name}, $bynick, $byuh, $last_topic{$chn_tag});
		delete $last_topic{$chn_tag};
		delete $last_topic_by{$chn_tag};
	}

	if ($chn->{topic} =~ m/^[ .]+$/) {
		$chn->command("TOPIC -delete");
		return;
	}

	if ($chn->{topic} ne '') {
		$last_topic{$chn_tag} = $chn->{topic};
		$last_topic_by{$chn_tag} = $chn->{topic_by};
	}
}

sub cmd_addtopic
{
	my ($param, $server, $chn) = @_;

	my $no_by = ($param =~ s/^-nb\s+//);

	if (!$chn or $chn->{type} ne 'CHANNEL') {
		my $chn_name;
		($chn_name, $param) = split(/\s/, $param);
		$chn = $server->channel_find($chn_name);
		if (!$chn) {
			Irssi::printformat(MSGLEVEL_CLIENTNOTICE, 'no_chan', $chn_name);
			return;
		}
	}

	my $topic = $chn->{topic};
	if ($topic ne '') {
		if (not $no_by and $topic !~ m/\/[][^|{}`a-zA-Z0-9_-]+$/) {
			my ($by, $uh) = split('!', $chn->{topic_by});
			$topic .= " /$by";
		}
		$topic .= " | ";
	}

	$topic .= $param;
	$chn->command("TOPIC $topic");
}

Irssi::signal_add_last('channel topic changed', 'sig_topic');
Irssi::command_bind('addtopic', 'cmd_addtopic');
