#!/usr/local/bin/perl5
#
# $Id: thread-status.pl,v 1.10 2009/02/01 09:12:09 winter Exp $

use HTTP::Cookies;
use HTML::Entities;
use WWW::Mechanize;
use HTML::TreeBuilder;
use Data::Dumper;
use Cfg;

sub
parse_topic
{
	my $t = shift;
	my ($div, $a, $topic, $url, @pages, $last_page);
	my (@rB, $author, $replies, $read);

	$div = $t->look_down('_tag' => 'div', 'class' => 'floatLeftTopic');
	if (!defined($div)) {
		return undef;
	}
	$a = $div->look_down('_tag' => 'a', 'style' => qr/.*/);
	$topic = $a->as_text;
	$url = $a->attr('href');

	@pages = $div->look_down('_tag' => 'a', 'class' => 'forumTextSmall');
	if ($#pages == -1) {
		$last_page = 1;
	} else {
		$last_page = $pages[$#pages]->as_text;
	}

	@rB = $t->look_down('_tag' => 'div', 'class' => 'repliesBox');
	$author = $rB[0]->as_text;
	$replies = $t->look_down('_tag' => 'div', 'class' => 'topicBox')->as_text;
	$read = $rB[1]->as_text;

	return {
		link	=> $site . "forums/" . $url,
		title	=> $topic,
		author	=> $author,
		replies	=> int($replies),
		read	=> int($read),
		last	=> int($last_page),
	}
}

sub
forum_findThread {
	my $forum = shift;
	my $thread = shift;

#print "Looking for " . $thread . "\n";

	$cookie_jar = HTTP::Cookies->new(
			file => "$ENV{'HOME'}/lwp_cookies.dat",
			autosave => 1,
		);

	# Hardcode to search the first 3 pages.
	for ($page = 1; $page < 15; $page++) {
		my $agent = WWW::Mechanize->new(cookie_jar => $cookie_jar);
		$agent->get(decode_entities($forum) . '&page=' . $page);

		my $root = HTML::TreeBuilder->new_from_content($agent->{content});
		my @topics = $root->look_down('_tag' => 'div', 
				sub { $_[0]->attr('class') eq 'forumTableDark' or
				      $_[0]->attr('class') eq 'forumTableLight' });
		# Users online
		pop @topics;
		# User info
		pop @topics;

		$i = 1;
		foreach $topic (@topics) {
			$t = parse_topic($topic);
			next if (!defined($t));

#		print "Page " . $page . " Topic " . $i . "\n";
#		print Dumper($t);

			if ($thread eq $t->{link}) {
				return $t;
			}
			$i++;
		}
	}
	return undef;
}

$t = forum_findThread($forumURL, $threadIndexURL) or die "thread not found";
print $t->{last} - 1 . "\n";
exit (0);
