package WebService::Idonethis;
use v5.010;
use strict;
use warnings;
use autodie;
use Moose;
use MooseX::Method::Signatures;
use WWW::Mechanize;
use JSON::Any;
use Carp qw(croak);

my $json = JSON::Any->new;

# ABSTRACT: WebScraping pseudo-API for iDoneThis

our $VERSION = '0.01'; # VERSION: Generated by DZP::OurPkg:Version


has agent    => ( is => 'rw' );
has user_url => ( is => 'rw' );

sub BUILD {
    my ($self, $args) = @_;

    my $agent = WWW::Mechanize->new;
    $agent->agent_alias ( "Linux Mozilla" );

    $self->agent( $agent );

    # Log in!

    $agent->get( "https://idonethis.com/accounts/login/" );

    $agent->submit_form(
        form_id => 'register',
        fields => {
            username => $args->{user},
            password => $args->{pass},
        }
    );

    my $url = $agent->uri;

    if ($url !~ m{/cal/$args->{user}/?$}) {
        croak "Login to idonethis failed (unexpected URL $url)";
    }

    $self->user_url( $url );

    return;

}


method get_day( Str $date) {
    my $url = $self->user_url . "dailydone?";

    $url .= "start=$date&end=$date";

    $self->agent->get($url);

    return $json->decode( $self->agent->content );
}

1;

__END__

=pod

=head1 NAME

WebService::Idonethis - WebScraping pseudo-API for iDoneThis

=head1 VERSION

version 0.01

=head1 METHODS

=head2 get_day

    $idt->get_day("2012-01-01");

Gets the data for a given day. An array will be returned which is a
conversation from the JSON data structure used by idonethis. The
structure at the time of writing looks like this:

    [
        {
            owner => 'some_user',
            avatar_url => '/site_media/blahblah/foo.png',
            modified => '2012-01-01T15:22:33.12345',
            calendar => {
                short_name => 'some_short_name', # usually owner name
                name => 'personal',
                type => 'PERSONAL',
            },
            created => '2012-01-01T15:22:33.12345',
            done_date => '2012-01-01',
            text => 'Wrote code to frobinate the foobar',
            nicest_name => 'some_user',
            type => 'dailydone',
            id => 12345
        },
        ...
    ]

=for Pod::Coverage BUILD

=head1 AUTHOR

Paul Fenwick <pjf@cpan.org>

=head1 COPYRIGHT AND LICENSE

This software is copyright (c) 2013 by Paul Fenwick.

This is free software; you can redistribute it and/or modify it under
the same terms as the Perl 5 programming language system itself.

=cut
