package Unalog;

use strict;
use warnings;
use LWP::UserAgent;
use URI;
use base qw( Class::Accessor );

## the master unalog URL
my $UNALOG_URL = 'http://unalog.mine.nu';

## autogenerate some basic accessors
Unalog->mk_accessors( qw( username password ) );

=head1 NAME

Unalog - Interact with the Unalog

=head1 SYNOPSIS

    use Unalog;
    my $ua = Unalog->new( username = 'me', password => 'hohoho' );
    $ua->add( 
        url     => 'http://www.google.com',
        title   => 'google',
        comment => 'my favorite search engine'
    );

=head1 DESCRIPTION

This is alpha software for routing links to unalog.mine.nu. The 
interface will very likely change.

=head1 METHODS

=head2 new()

Logs into unalog using the C<username> and C<password> that are passed
in.

    my $unalog = Unalog->new( username => 'me', password => 'ins3cur3' );

=cut 

sub new {
    my ( $class, %opts ) = @_;
    my $self = bless {}, ref( $class ) || $class;
    $self->username( $opts{ username } );
    $self->password( $opts{ password } );
    $self->_init() || return( undef );
    return( $self );
}

=head2 add()

Add will add a site to your unalog account. You must pass in C<url>
and C<title> parameters; C<comment> is optional.

    $unalog->add( 
        url     => 'http://www.google.com',
        title   => 'google',
        comment => 'my favorite search engine'
    );

=cut

sub add {
    my ( $self, %options ) = @_;
    croak( "must pass in url parameter" ) 
        if ! exists( $options{ url } );
    croak( "must pass in title parameter" )
        if ! exists( $options{ title } );
    my $uri = URI->new( "$UNALOG_URL/my/stack/link" );
    $uri->query_form(
        title   => $options{ title },
        url     => $options{ url },
        comment => $options{ comment },
        stack   => 'stack',
    );
    my $response = $self->{ ua }->get( $uri );
    return( undef ) if $response->is_error();
    return( 1 );
}

=head1 AUTHORS

=over 4

=item * Dan Chudnov <dchud@umich.edu>

=item * Ed Summers <ehs@pobox.com>

=back

=cut


## internal subroutine for logging in to unalog

sub _init {
    my $self = shift;
    my $ua = LWP::UserAgent->new();

    ## agent needs to store cookies 
    $ua->cookie_jar( { } ); 

    ## login
    my $response = $ua->post( 
        "$UNALOG_URL/my/login",
        [ 
            user_id     => $self->username(), 
            user_pass   => $self->password(),
            login       => 'login',
            name        => 'go'

        ]
    );

    ## uhoh problem
    return( undef ) if $response->is_error();

    ## stash our primed user agent away
    $self->{ ua } = $ua; 
}

1;
