package Plagger::Plugin::CustomFeed::Femo;

use strict;
use base qw( Plagger::Plugin );
use Plagger::Mechanize;
use Encode qw/decode_utf8/;

sub register {
    my($self, $context) = @_;
    $context->register_hook(
        $self,
        'subscription.load' => \&load,
    );
}

sub load {
    my($self, $context) = @_;
    $self->{mech} = Plagger::Mechanize->new( cookie_jar => $self->cookie_jar );

    my $feed = Plagger::Feed->new;
    $feed->aggregator( sub { $self->aggregate(@_) } );
    $context->subscription->add($feed);
}

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

    unless( $self->login( id => $self->conf->{id}, password => $self->conf->{password},) ) {
	$context->log(error => "Login failed.");
	return;
    }

    $context->log(info => 'Login to Femo succeeded');

    my $res = $self->retrieve($self->conf->{tag});

    my $feed = Plagger::Feed->new;
    $feed->type('femo');
    $feed->title('Femo : '.$self->conf->{id});
    $feed->link('http://femo.jp/');

    my $parser = XML::LibXML->new();
    my $doc = $parser->parse_html_string($res->content);
    my $format = DateTime::Format::Strptime->new(pattern => '%Y-%m-%d %T');

    foreach my $entry ($doc->findnodes("//div[\@class='entry']")) {
	my @title = $entry->findnodes("h2[\@class='entry-header']/a/text()");
	my @tags = $entry->findnodes(q!div[@class='entry-content']/p[@class='entry-tags']/span/a/text()!);
	my @body = $entry->findnodes(q!div[@class='entry-content']/div[@class='entry-body']!);
	my @footer = $entry->findnodes(q!div[@class='entry-content']/p[@class='entry-footer']!);

        my $entry = Plagger::Entry->new;
        $entry->title( decode_utf8($title[0]->nodeValue) );
        $entry->author($self->conf->{id});

	my $footer = $footer[0]->toStringC14N;
	if($footer =~ m!\d{4}-\d\d-\d\d \d\d:\d\d:\d\d!){
	    $entry->date( Plagger::Date->parse( $format, $&) );
	}
	if($footer =~ m!EditEntry\((\d+),!){
	    $entry->link('http://femo.jp/#'.$1);
	}

	$entry->body( decode_utf8($body[0]->toStringC14N) );
	$entry->tags([ map{ decode_utf8($_->nodeValue) } @tags ]);

        $feed->add_entry($entry);

    }

    $context->update->add($feed) if $feed->count;
}

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

    $self->{mech}->get('http://femo.jp/');
    return 1 if $self->{mech}->content =~ /pref-target/;

    Plagger->context->log(debug=>'Cookie not found. login to Femo');
    $self->{mech}->get('http://femo.jp/do_login');
    return 1 if $self->{mech}->content =~ /pref-target/;
    return 0 if $self->{mech}->content !~ m!/t/typekey!;

    Plagger->context->log(debug => 'Login to TypeKey');
    $self->{mech}->submit_form(
	form_number=>1,
	fields => {
	    username => $args{id},
	    password => $args{password}
	}
    );
    return 0 unless $self->{mech}->content !~ /pref-target/;

    return 1;
}

sub retrieve{
    my ($self, $tag) = @_;

    my %query_form =(
	sort_order=>1,
    );
    $tag = Plagger::Date->now->ymd if (defined $tag && $tag eq "__TODAY__");
    $query_form{tag} = $tag if defined $tag;

    my $uri = URI->new('http://femo.jp/entries/list');
    $uri->query_form(%query_form);
    Plagger->context->log(debug => $uri);
    my $res = $self->{mech}->get($uri);
    return $res;
}

1;


1;
__END__

=head1 NAME

Plagger::Plugin::CustomFeed::Femo -

=head1 SYNOPSIS

  - module: CustomFeed::Femo

=head1 DESCRIPTION

XXX Write the description for CustomFeed::Femo

=head1 CONFIG

XXX Document configuration variables if any.

=head1 AUTHOR

Masahiro Nagano

=head1 SEE ALSO

L<Plagger>

=cut
