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 has_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->has_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->_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->discid;

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

sub _get_cdparanoia_span {
    my ($self) = @_;
    # use a msf start unless track 1 begins at sector
    return $self->tracks->tracks->[1]{sector} == 0 ? '1-' : '00:00.00-';
}

# module return
1;
