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

$VERSION = '1.03';
%IRSSI = (
	authors 	=> 'Eric Jansen',
	contact 	=> 'chaos@sorcery.net',
	name 		=> 'imdb',
	description 	=> 'Automatically lookup IMDB-numbers in nicknames',
	commands	=> '',
	license 	=> 'GPL',
	modules		=> 'LWP::UserAgent',
	changed 	=> 'Thu Oct  2 21:19:56 CEST 2003'
);

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

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}) {

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

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

				$channel->printformat(MSGLEVEL_CRAP, 'imdb', $old_nick, $cache->{$id}->{'title'}, $cache->{$id}->{'year'});
			}
		}
		else {
			my $req = new HTTP::Request(GET => "http://www.imdb.com/title/tt$id/");
			my $res = $ua->request($req);

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

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

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

				if($res->content =~ /User Rating:.*?<b>([\d\.]+)\/10<\/b> \(([\d\,]+) votes\)/s) {

					($rating, $votes) = ($1, $2);

					$channel->printformat(MSGLEVEL_CRAP, 'imdb_rating', $old_nick, $title, $year, $rating, $votes);
				}
				else {

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

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

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