package Ripper;

use Moose;

use Tracks;

use File::Temp qw{tempdir};
use File::Spec::Functions qw{catfile};
use File::Copy;

has device => ( is => 'rw' );
has tracks => ( 
    is => 'rw',
    handles => [qw{read_disc get_tracks get_cuesheet}],
);

sub rip_to_flac {
    my ($self, $archive_flac) = @_;

    $self->tracks(Tracks->new);
    $self->read_disc($self->device);

    die "No tracks found; is there a CD in the drive?\n" unless @{ $self->get_tracks };

    my $tempdir = tempdir(CLEANUP => 1);

    my $wav_file  = catfile($tempdir, 'cdda.wav');
    my $flac_file = catfile($tempdir, 'cdda.flac');
    my $cue_file  = catfile($tempdir, 'cdda.cue');

    # rip
    my $span = $self->tracks->get_cdparanoia_span;
    system 'cdparanoia', '-d', $self->device, $span, $wav_file;
    die "\nRipping canceled\n" if ($? & 127);

    # encode + cuesheet
    open my $CUE, "> $cue_file";
    print $CUE $self->get_cuesheet;
    close $CUE;
    system 'flac', '-o', $flac_file, '--cuesheet', $cue_file, $wav_file;
    die "\nFLAC encoding canceled\n" if ($? & 127);

    # MusicBrainz discid metadata
    my $discid = $self->tracks->get_mbz_discid;

    # copy to permanent location
    copy($flac_file, $archive_flac);
    system 'metaflac', '--set-tag', "MUSICBRAINZ_DISCID=$discid", $archive_flac;
}

# module return
1;
