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

$VERSION = "0.2";
%IRSSI = (
    authors     => 'Sam Hocevar',
    contact     => 'sam\@zoy.org',
    name        => 'Wikilinks',
    description => 'Simple script that translates wiki links to URLs',
    license     => 'WTFPL',
    url         => 'http://sam.zoy.org/wikipedia/',
    changed     => '$Id: blah$'
);

my %chan2lang = (
   '#wikipedia-da' => 'da',
   '#wikipedia-darc' => 'da',
   '#wikipedia-de' => 'de',
   '#wikipedia-derc' => 'de',
   '#wikipedia-es' => 'es',
   '#wikipedia-esrc' => 'es',
   '#wikipedia-fr' => 'fr',
   '#wikipedia-frrc' => 'fr',
   '#wikimedia-fr' => 'fr',
);

sub linkify {
    my ($a, $link, $b, $name, $c, $remain, $target) = @_;
    my $lang = $chan2lang{$target} || 'en';
    my $ret = "$a\x0306\x02$link\x0f$b\x0306\x02$name\x0f$c$remain";
    $link =~ s/([%"&!\$&\(\)\*\+=\?^#'])/'%' . unpack("H*", $1)/eig;
    $link =~ y/ /_/;
    $ret .= " (\x0306http://$lang.wikipedia.org/wiki/$link\x0f)";
    return $ret;
}

sub wikilinks {
    my ($server, $data, $nick, $mask, $target) = @_;
    my $win = Irssi::window_find_name($target);
    my $lang = 'en';
    if (!defined($win)) {
        $win = Irssi::window_find_refnum(1);
    }
    $data =~ s!(\[\[ *)([^\]\|]*[^\]\| ])( *\|? *)([^\]]*)( *\]\])(\w*)!linkify($1, $2, $3, $4, $5, $6, $target)!ge;
    Irssi::signal_continue($server, $data, $nick, $mask, $target);
}

Irssi::signal_add('message irc action', 'wikilinks');
Irssi::signal_add('message public', 'wikilinks');
Irssi::signal_add('message private', 'wikilinks');
Irssi::signal_add('message topic', 'wikilinks');
Irssi::signal_add('message irc own_action', 'wikilinks');
Irssi::signal_add('message own_private', 'wikilinks');
Irssi::signal_add('message own_public', 'wikilinks');

