# This is GPL code
# Copyright (C) 2008 Petschge <mail@petschge.de>
#

use Irssi;
use Irssi::Irc;
use vars qw($VERSION %IRSSI);
use Algorithm::Diff qw( sdiff );

$VERSION = "0.01";
%IRSSI = (
	authors     => "petschge",
	contact     => "mail\@petschge.de",
	name        => "topic diff",
	description => "Shows what the difference to the old topic is",
	license     => "GNU GPLv2",
);

my %topiclist = ();

sub event_topic {
	my ($server, $data, $nick, $address) = @_;
	my ($channel, $topic) = split(/ :/, $data, 2);
	my $tag = $server->{'tag'};

        my $window = Irssi::window_find_name('(status)');
	my $text;

	if($topiclist{lc($tag)}{lc($channel)}) {
		my @seq1 = split(/ /, $topiclist{lc($tag)}{lc($channel)});
		my @seq2 = split(/ /, $topic);
		my @sdiff = sdiff( \@seq1, \@seq2 );
		my @shortm;
		my @short1;
		my @short2;
		my $i = 0;
		my $lastmod = "";
		while (@sdiff and my ($mod, $s1, $s2) = @{shift @sdiff}) {
			if($mod eq $lastmod) {
				my $a1 = $short1[$i];
				my $a2 = $short2[$i];
				$short1[$i] = $a1 ." ". $s1;
				$short2[$i] = $a2 ." ". $s2;
			} else {
				$i++;
				$shortm[$i] = $mod;
				$short1[$i] = $s1;
				$short2[$i] = $s2;
				$lastmod = $mod;
			}
		}
		my $change = "";	
		for($i = 1; $i < @shortm; $i++) {
			if($shortm[$i] eq "u") {
				$change .= $short1[$i]." ";
			} elsif ($shortm[$i] eq "c") {
				$change .= "\"".$short1[$i]."\"=>\"".$short2[$i]."\" ";
			} elsif ($shortm[$i] eq "-") {
				$change .= " (".$short1[$i].")- ";
			} elsif ($shortm[$i] eq "+") {
				$change .= " (".$short2[$i].")+ ";
			}
		}

        	$text = "net: $tag, channel: $channel, topic change: $change";
	} else {
        	$text = "net: $tag, channel: $channel, topic set to $topic";
	}
       	$window->print($text, MSGLEVEL_CLIENTCRAP) if ($window);

        $topiclist{lc($tag)}{lc($channel)} = $topic;
}


Irssi::signal_add("event topic", "event_topic");

Irssi::print("Loaded topicdiff.pl v$VERSION");

