package BookPub::Import::Importer::BlackstoneAudio::Version4;

use strict;
use Data::Dumper;

use lib '/app/tools/bookpub/lib';
use base 'BookPub::Import::Importer';

sub _headerIdentifier { ( rTitle => 'Title' ) }

sub _fieldMap {
    {
        rIsbn13    => 'F',
        rTitle     => 'D',
        rAuthor    => 'E',
        rUnits     => 'G',
        rListPrice => 'H',
        rDiscount  => 'J',
        rRevenue   => 'K',
    };
}

sub _getDateBegin      { shift->{_dateBegin} }
sub _dateFormat        { [ 'text', 'iso' ] }
sub _dateNormalization { 'month' }
sub countryCode        { 'US' }
sub currencyCode       { 'USD' }
sub priceType          { 'rrp' }
sub productType        { BookPub::DB::Item::Sale::kProductTypeAudioBook }
sub purchaseType       { BookPub::DB::Item::Sale::kPurchaseTypeDownload }

sub _processLine {
    my $self = shift;
    my $isbn = $self->_getByFieldName('rIsbn13');

    if ( $isbn && $isbn =~ m/ISBN/ ) {
        $self->{_endOfData} = 1;
        return undef;
    } else {
        return $self->SUPER::_processLine(@_);
    }
}

sub _preProcess {
    my $self = shift;
    my %args = @_;

    Log->info("Starting _preProcess");
    $self->SUPER::_preProcess(%args);

    # Since the date varies in placement in the file, let's try the filename.
    if ( !$self->{_dateBegin} ) {
        my $filename = $self->filename;
        if ( $filename =~ m/ (\w+ \d{4})\.xlsx$/i ) {
            $self->{_dateBegin} = "$1";
        }
    }

    # Still didn't find it?  Give up.
    if ( !$self->{_dateBegin} ) {
        $self->errstr('Unable to find date');
        return undef;
    }

}

sub rIsbn13 {
    my $self = shift;
    my $isbn = $self->_getByFieldName('rIsbn13');

    $isbn =~ s/-//g;

    return $isbn;
}

sub rDiscount {
    my $self = shift;

    my $discount = $self->_getByFieldName('rDiscount');
    $discount =~ s/%//;
    $discount = 1 - $discount;

    return $discount;
}

###
1;    # Play nicely.
###
