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

use Audio::ConvTools;
use File::Basename;
use File::stat;
use File::Copy;
use File::Spec;

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

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

    my $from = $self->conf->{from};
    my $to   = $self->conf->{to};

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

    {
        no strict 'refs';
        *convert = *{ $from . '2' . $to };
    }

    my $local_path = eval { $e->enclosure->local_path };
    if($@){
        $context->log(error => q{Can't get local path.} );
        return;
    }

    my $basename = basename($local_path, $from);
    my $local_dir = dirname($local_path);
    my $converted_file = File::Spec->catfile($self->conf->{dir}, $basename . $to);

    unless ( -e $converted_file ){
        my $status = convert($local_path);
        unless ( $status ) {
            $context->log(error => "Could not convert $local_path" );
            return;
        }
    }

    my $converted_file_before_move = File::Spec->catfile( $local_dir, $basename . $to );
    if($self->conf->{normalize}){
        my $vol = `sox $converted_file_before_move -e stat -v 2<&1`;
        chomp $vol;
        system('sox', '-v', $vol, $converted_file_before_move, $converted_file);
    }
    else {
        move( $converted_file_before_move, $converted_file );
    }

    my $st = stat($converted_file);
    $e->enclosure->length($st->size);
    $e->enclosure->local_path($converted_file);
    $e->enclosure->filename($basename . $to);
    $e->enclosure->type( Plagger::Util::mime_type_of($to) );
}

1;
__END__

=head1 NAME

Plagger::Plugin::Filter::Audio - Convert enclosure audio files with Audio::ConvTools.

=head1 SYNOPSIS

  - module: Filter::Audio
    config:
      dir: /home/miya/audio
      from: ogg
      to: mp3
      normalize: 1

=head1 DESCRIPTION

XXX Write the description for Filter::Audio

=head1 CONFIG

XXX Document configuration variables if any.

=head1 AUTHOR

Gosuke Miyashita

=head1 SEE ALSO

L<Plagger>, L<Audio::ConvTools>

=cut
