use Irssi;
use LWP::UserAgent;
use strict;
use vars qw($VERSION %IRSSI $cache);

$VERSION = '1.02';
%IRSSI = (
    authors 	=> 'Eric Jansen',
    contact 	=> 'chaos@sorcery.net',
    name 	=> 'imdb',
    description => 'Automatically lookup IMDB-numbers in nicknames',
    commands	=> '',
    license 	=> 'GPL',
    modules	=> 'LWP::UserAgent',
    changed 	=> 'Tue May 27 20:24:39 CEST 2003'
);

my $ua = new LWP::UserAgent;
$ua->agent('Irssi; ' . $ua->agent);
$ua->timeout(1);

sub event_nickchange
{
    my ($channel, $nick, $old_nick) = @_;

    if($nick->{'nick'} ne $channel->{'ownnick'}->{'nick'} && $nick->{'nick'} =~ /\D(\d{7})(?:\D|$)/) {

	my $id = $1;

	if(defined $cache->{$id}) {

	    $channel->printformat(MSGLEVEL_CRAP, 'imdb_lookup', $old_nick, $cache->{$id}->{'title'}, $cache->{$id}->{'year'});
	}
	else {

    	    my $req = new HTTP::Request(GET => "http://us.imdb.com/Title?$id");
	    my $res = $ua->request($req);

    	    if($res->is_success && $res->content =~ /<title>(.+?) \((\d+)\)<\/title>/) {

		my ($title, $year) = ($1, $2);

		$title =~ s/&#(\d+);/pack('C*', $1)/eg;

		$channel->printformat(MSGLEVEL_CRAP, 'imdb_lookup', $old_nick, $title, $year);

		$cache->{$id} = {
		    'title'	=> $title,
		    'year'	=> $year
		};
	    }
	}
    }
}

Irssi::theme_register([
    'imdb_lookup', '{nick $0} is watching {hilight $1} ($2)'
]);
Irssi::signal_add('nicklist changed', 'event_nickchange');
