# $Id: EnclosureImageSize.pm 113 2007-08-27 15:22:40Z mayuki $
package Plagger::Plugin::Filter::EnclosureImageSize;
use strict;
use base qw( Plagger::Plugin );

use Image::Size;

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

    $context->register_hook(
        $self,
        'update.entry.fixup' => \&filter
    );
}

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

    my $e = $args->{entry};

    if ($e->has_enclosure) {
        for my $enclosure (grep { -e $_->local_path } $e->enclosures) {
            my ($width, $height, $type, $drop);
            eval { ($width, $height, $type) = imgsize($enclosure->local_path); };
            next unless $width && $height;

            $context->log(debug => "Image Size: $width x $height, Type: $type");
            if ($self->conf->{min_height} && $self->conf->{min_height} > $height) {
                $drop = 1;
                $context->log(debug => "MinHeight: " . $self->conf->{min_height} . " px");
            }
            if ($self->conf->{min_width} && $self->conf->{min_width} > $width) {
                $drop = 1;
                $context->log(debug => "MinWidth: " . $self->conf->{min_width} . " px");
            }
            if ($self->conf->{max_height} && $self->conf->{max_height} < $height) {
                $drop = 1;
                $context->log(debug => "MaxHeight: " . $self->conf->{max_height} . " px");
            }
            if ($self->conf->{max_width} && $self->conf->{max_width} < $width) {
                $drop = 1;
                $context->log(debug => "MaxWidth: " . $self->conf->{max_width} . " px");
            }
            if ($self->conf->{type} && $type =~ /$self->conf->{type}/i) {
                $drop = 1;
                $context->log(debug => "Type: " . $self->conf->{type});
            }

            if ($drop) {
                $context->log(info => "Drop enclosure/file " . $enclosure->local_path);

                $e->{enclosures} = [ grep { $_->local_path ne $enclosure->local_path } $e->enclosures ];
                unlink $enclosure->local_path
                    or $context->log(error => "can't remove file '".$enclosure->local_path."'");
            }
        }
    }
}

1;
__END__

=head1 NAME

Plagger::Plugin::Filter::EnclosureImageSize - 

=head1 SYNOPSIS

- module: Filter::FindEnclosures
- module: Filter::FetchEnclosure
- module: Filter::EnclosureImageSize
  config:
    min_height: 100
    min_width: 100

=head1 DESCRIPTION

[ato de kaku]

=head1 CONFIG

=head1 AUTHOR

Mayuki Sawatari

=head1 SEE ALSO

L<Plagger>, L<Plagger::Plugin::Filter::FetchEnclosure>

=cut
