package Plagger::Plugin::Filter::Lame;
use strict;
use base qw(Plagger::Plugin::Filter::Base);

sub register {
    my($self, $context) = @_;
    $context->register_hook(
        $self,
        'update.entry.fixup' => \&filter,
    );
}

sub init {
    my $self = shift;
    $self->SUPER::init(@_);

    defined $self->conf->{dir} or Plagger->context->error("config 'dir' is not set.");
    unless (-e $self->conf->{dir} && -d _) {
        Plagger->context->log(warn => $self->conf->{dir} . " does not exist. Creating");
        mkpath $self->conf->{dir};
    }
}

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

    for my $enclosure ($args->{entry}->enclosures) {
        my $feed_dir = File::Spec->catfile($self->conf->{dir}, $args->{feed}->id_safe);
        unless (-e $feed_dir && -d _) {
            $context->log(info => "mkdir $feed_dir");
            mkdir $feed_dir, 0777;
        }

        my $srcpath = $enclosure->local_path;
        $srcpath =~ m/(.*)\./;
        my $dstpath = $1 || $srcpath;
        $dstpath .= '.mp3';

        if (-e $dstpath) {
            my $length = -s _;
            $enclosure->length($length);
            $enclosure->type('audio/x-mp3');
            $enclosure->local_path($dstpath);
            $context->log(debug => $srcpath. "is already converted into $dstpath");
            next;
        }

        unless (-e $srcpath) {
            $context->log(info => "The local data has not stored yet.");
            next;
        }

        $context->log(info => "Convert " . $srcpath . " to " . $dstpath);

        my @options = split(/ /,$self->conf->{option}) or ('-V5', '--athaa-sensitivity', '1');
        my @command = ('lame', @options, $srcpath, $dstpath);

        system(@command);

        if (!$? && -s $dstpath ) {
            my $length = -s _;
            $enclosure->length($length);
            $enclosure->type('audio/x-mp3');
            $enclosure->local_path($dstpath);
            $context->log(info => "Converting to $dstpath is done [$length]");
            if ($self->conf->{delsrc}) {
                $context->log(info => "Deleting $srcpath");
                unlink $srcpath or $self->log(error => "Cannot delete $srcpath. ");
            }
        }
    }
}

1;

__END__

=head1 NAME

Plagger::Plugin::Filter::Lame - Convert local files to mp3  using lame

=head1 SYNOPSIS

  - module: Filter::Lame
    config:
      dir: /path/for/convert
      option: -lame -options  
      delsrc: 1


=head1 DESCRIPTION

This plugin converts fetched files to mp3 files using lame.

=head1 AUTHOR

Yohei Fushii

=head1 SEE ALSO

L<Plagger>

=cut
