package Modsde::Thread;

use Modsde::Post;
use base "Modsde";


__PACKAGE__->mk_accessors(qw/tid lastPage/);

sub new {
	my ($self, $options) = @_;
	unless($options->{tid} =~ /^\d+$/) {
		die "Now TID given to " . __PACKAGE__ . '->new()';
	}
	$self = $self->SUPER::new($options);
	$self->{pages} = [];
	return $self;
}

sub fetch {
	my $self = shift;

	unless( $self->{thread} ) {
		$self->debug("Going to fetch thread with tid " . $self->tid);
		my $uri = 'http://forum.mods.de/bb/thread.php?TID='.$self->tid;
		$self->debug("URI [$uri]");
		$self->mech->get($uri);
		$self->{thread} = $self->mech->content;
		die "Thread is hidden or doesn't exists!" if($self->{thread} =~ /Dieser Thread wurde noch nicht freigeschaltet oder er wurde versteckt!/);
		$self->pages;
		$self->{pages}->[1] = $self->{thread};
	}
	return $self->{thread};
}

sub fetchPage {
	my ($self, $nr) = @_;
	die "No page to fetch!" unless($nr);

	$self->fetch;

	die "Page ($nr) bigger than last page (".$self->lastPage.") of thread" if($nr > $self->lastPage);

	unless($self->{pages}->[$nr]) {
		$self->debug("Retrieve page $nr from Server");
		$self->mech->get(sprintf('http://forum.mods.de/bb/thread.php?TID=%d&page=%d&override=', $self->tid, $nr));
		$self->{pages}->[$nr] = $self->mech->content;
	}
	return $self->{pages}->[$nr];
}

sub title {
	my $self = shift;
	my $content = $self->fetch;
	
	if(!defined $self->{title}) {
		$self->debug("So far now ThreadTitle parsed, let's search...");
		#<b>&nbsp;Thema: -= MTA 59  =- die nächste Fahrt geht rückwärts! <i>(</i> ...auf gehts ab gehts, von Do-So wach !!! <i>)</i></b><br/>
		if($content =~ m!<b>&nbsp;Thema: (.*?)\s+(?:<i>\(</i> (.*?) <i>\)</i>)?</b>!) {
			$self->debug("Title is: [$1]");
			$self->debug("SubTitle is [$2]") if($2);
			$self->{title} = $1;
			$self->{subtitle} = $2;
		}
		else {
			$self->debug("Sorry, found no Title!");
		}
	}
	return $self->{title};
}

sub pages {
	my $self = shift;

	my $content = $self->fetch;
	my $tid = $self->tid;
	
	if($content =~ m~&page=(\d+)'>letzte &raquo;</a>~) { #'
	$self->debug("LastPage $1 based on 'letzte'\n");
	$lastPage = $1;
	}
	#thread.php?TID=199791&page=8&override='>8</a> <a href='thread.php?TID=199791&page=2&override='>nächste &raquo;</a>
	elsif($content =~ m~(\d+)</a>\s*<a href='[^']+'>n~i) { # '
		$self->debug("LastPage $1 based on 'nächste'\n");
		$lastPage = $1;
	}
	else {
		$self->debug("LastPage = 1, only one page\n");
		$lastPage = 1;
	}

	$self->lastPage($lastPage);

	return $lastPage;
}

sub getNewPostsByTime {
	my ($self, $dt) = @_;
	die "Not a DateTime Object!" unless(UNIVERSAL::isa($dt, "DateTime"));

	$self->fetch();
	my @newPosts;
	foreach( reverse 1 .. $self->lastPage) {
		my @posts = $self->postsOnPage($_);
		my @new = grep { $_->posted > $dt } @posts;
		push(@newPosts, @new);
		last if(scalar(@posts) > scalar(@new));
	}
	return reverse @newPosts;
}

sub getNewPostsByPid {
	my ($self, $pid) = @_;
	die "pid [$pid] is not a valid PID" unless($pid =~ /^\d+$/);

	$self->fetch();
	my @newPosts;
	foreach( reverse 1 .. $self->lastPage) {
		my @posts = $self->postsOnPage($_);
		my @new = grep { $_->pid > $pid} @posts;
		push(@newPosts, @new);
		last if(scalar(@posts) > scalar(@new));
	}
	return reverse @newPosts;
}

sub postsOnPage {
	my ($self, $pagenr) = @_;
	die "Invalid or no page number" unless($pagenr =~ /^\d$/);
	
	$self->fetch;
	die "page number bigger than last page" if($pagenr > $self->lastPage);

	$self->debug("Getting posts on page $pagenr");
	
	my @posts;
	my $page = $self->fetchPage($pagenr);
	my @data = ($page =~ m~reply_(\d+).*?openProfile2?\((\d+)\)'>(?:<s>)?([^<]+?)(?:</s>)?</a>.*?#reply_\1.*?(\d{1,2}\.\d{1,2}\.\d{4} \d{1,2}:\d{1,2}:\d{1,2})~gs); #'
	$self->debug("Found " . @data/4 . " posts");
	for(my $i = scalar(@data)-4; $i >= 0; $i-= 4) {
		my ($pid, $uid, $username, $time) = @data[$i, $i+1, $i+2, $i+3];
		my $post = Modsde::Post->new(
			{
				uid		=> $uid,
				username	=> $username,
				pid		=> $pid,
				posted	=> $time,
			}
		);
		push(@posts, $post);
		$self->debug("PID: " . $post->pid . ", User: ". $post->username);
	}
	
	return @posts;
}

sub posts {
	my $self = shift;

	$self->debug("Fetching all posts");

	$self->fetch;
	
	my @posts;
	foreach(reverse(1 .. $self->lastPage)) {
		push(@posts, $self->postsOnPage($_));
	}

	return reverse @posts;
}

1;
