package Modsde;

use strict;
use warnings;
use base 'Class::Accessor';

sub login {
	my $self = shift;
	my ($user, $pass) = @_;

	my $m = $self->mech;

	$m->get('http://forum.mods.de/bb/misc.php?view=login');
	$m->form_name('loginform');
	$m->set_visible($user, $pass, 30);
	$m->submit;
	# After logging in, we get to a page with a lot of iframes
	# which looks like a workaround, to set all cookies for all pages
	# of the mods.de network. So grab them all and visit them.
	#<iframe src="http://www.tf2.de/setcookie.php?u=15956&p=48ca47f19a614f4aa8505533f640212a&e=30"
	foreach($m->content() =~/<iframe src="(.*?)"/gis) {
		eval {
			$m->get($_);
		};
	}
	# Thanks to igor and cms, the logged-in-check is now bulletproof :p
	$m->get('http://forum.mods.de/bb/newreply.php?TID=140831&SID=');

	my $doc = join('',$m->content());
	if($doc =~ /Nicht genug Privilegien um einen Beitrag zu erstellen!/) {
		die "Login failed! - Probably a Cookie Problem\n";
	}
	$self->debug("Login successfull!");
}

sub mech {
	my $self = shift;
	my $m = $self->{mech};
	unless($m) {
		$self->debug("Creating new Mech");
		$m = WWW::Mechanize->new(
			agent => 'GH@NDI\'s ForenParser - Complaints? -> sven@sveneppler.de',
		);

		$m->stack_depth(1);
	}
	$self->{mech} = $m;
	return $self->{mech};
}

sub debug {
	my $self = shift;
	if($ENV{DEBUG}) {
		print "[DEBUG] ",@_,"\n";
	}
}

1;
