package Plagger::Plugin::SmartFeed::ImageGather;
use strict;
use base qw( Plagger::Plugin );

sub register {
    my($self, $context) = @_;
    $context->register_hook(
        $self,
        'smartfeed.init'  => \&feed_init,
        'smartfeed.entry' => \&feed_entry,
        'smartfeed.finalize' => \&feed_finalize,
    );
}

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

    my $feed = Plagger::Feed->new;
    $feed->type('smartfeed');
    $feed->id( $self->conf->{id} || ('smartfeed:' . $self->rule->id) );
    $feed->title( $self->conf->{title} || "Entries " . $self->rule->as_title );

    $self->{feed} = $feed;
}

sub feed_entry{
    my($self, $context, $args) = @_;
    my $body = $args->{entry}->body;

    while($body =~ m!<img([^>]+)>!g){
	$self->gathering($&,$context,$args);
    }
}

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

    my %attrs;
    while ($tag =~ m!(\w+)\s*=\s*(["'])(.*?)\2!g) {
	$attrs{$1} = $3;
    }
    
    return unless $attrs{src};
    
    my $entry = Plagger::Entry->new;
    $entry->title($attrs{title} || $attrs{alt} || $args->{entry}->title);
    $entry->link($attrs{src});
    $entry->author($args->{entry}->author);
    $entry->date($args->{entry}->date->clone);
    $entry->body($tag);

    $self->{feed}->add_entry($entry);
}

sub feed_finalize {
    my($self, $context, $args) = @_;
    $context->update->add($self->{feed}) if $self->{feed}->count;
}

1;




