# WWW::SourceForge.JP
# by hylom
# This code is under GPL.
#

use LWP;
use HTTP::Cookies;
use HTTP::Request::Common;
use otp::attach;

package Otp;

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 = 'http://magazine.sourceforge.jp/login.pl';
my $logout_url = 'http://magazine.sourceforge.jp/my/logout';
my $default_cookies = 'otp_cookies.txt';

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 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 = {
				   'op' => 'userlogin',
				   'unickname' => $login_name,
				   'upasswd' => $password,
				   'userlogin' => 'ログイン',
				  };
  my $resp = $ua->post( $login_url, $form_data );
}

sub logout {
  my $self = shift @_;

  my $ua = $self->lwp_ua;
  $ua->get( $logout_url );
}

sub Attach {
  my $self = shift @_;

  if ( ! defined $self->{_attach} ) {
    $self->{_attach} = Otp::Attach->new( $self );
  }

  return $self->{_attach};
}

1;
