# WWW::SourceForge.JP
# by hylom
# This code is under GPL.
#

use LWP;
use HTTP::Cookies;
use HTTP::Request::Common;
use SourceForgeJP::Wiki;

package WWW::SourceForgeJP;

my $ua_string = 'Mozilla/5.0 (Windows; U; Windows NT 6.0; ja; rv:1.9.0.1) Gecko/2008070208 Firefox/3.0.1';
my $login_url = 'https://sourceforge.jp/account/login.php';
my $logout_url = 'https://sourceforge.jp/account/logout.php';
my $default_cookies = $ENV{"HOME"} . "/" . '.sfjp_cookies';

sub new {
  my $class = shift @_;
  my $self = {
			  'useragent' => $ua_string,
			  'cookies_file' => $default_cookies,
			 };
  return bless $self, $class;
}

# getter/setter
sub useragent {
  my $self = shift @_;
  return $self->{useragent};
}

sub cookies_file {
  my $self = shift @_;
  return $self->{cookies_file};
}

sub _get_project_dir {
  my $self = shift @_;
  my $project = shift @_;

  return 'http://sourceforge.jp/projects/' . $project;
}

sub lwp_ua {
  my $self = shift @_;

  my $ua = LWP::UserAgent->new( 'agent' => $self->useragent, );
  my $cookie_jar = HTTP::Cookies->new( file => $self->cookies_file, autosave => 1, ignore_discard => 1, );
  $ua->cookie_jar( $cookie_jar );

  return $ua;
}

sub login {
  my $self = shift @_;
  my $login_name = shift @_;
  my $password = shift @_;

  my $ua = $self->lwp_ua;

  my $form_data = {
				   'return_to' => '/',
				   'login' => '1',
				   'form_loginname' => $login_name,
				   'form_pw' => $password,
				   'stay_in_ssl' => '1',
				  };
  my $resp = $ua->post( $login_url, $form_data );

  if ( $resp->is_error ) {
	print $resp->as_string;
	return 0;
  } else {
	return 1;
  }

}

sub logout {
  my $self = shift @_;

  my $ua = $self->lwp_ua;
  $ua->get( $logout_url );
}

sub Wiki {
  my $self = shift @_;

  if ( ! defined $self->{_wiki} ) {
    $self->{_wiki} = WWW::SourceForgeJP::Wiki->new( $self );
  }

  return $self->{_wiki};
}

1;

