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

use strict;
use Data::Dumper;

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

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

sub _fieldMap {
    my $self = shift;

    my %fieldMap = (
        5 => {
            rIsbn13    => 'F',
            rTitle     => 'D',
            rAuthor    => 'E',
            rUnits     => 'G',
            rListPrice => 'H',
            rDiscount  => 'J',
            rRevenue   => 'M',
        },
    );

    return $fieldMap{ $self->_version() };
}

sub _unverifiedFieldMap {
    my $self = shift;

    my %fieldMap = (
        5 => {
            downloadCol     => 'K',
            subscriptionCol => 'L',
        },
    );

    return $fieldMap{ $self->_version() };
}

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

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;
}

sub purchaseType {
    my $self = shift;

    my $downloadCol     = $self->_getByFieldName('downloadCol');
    my $subscriptionCol = $self->_getByFieldName('subscriptionCol');

    if ( $downloadCol && $subscriptionCol ) {
        $self->fail("Unable to determine purchase type");
    } elsif ($downloadCol) {
        return BookPub::DB::Item::Sale::kPurchaseTypeDownload;
    } elsif ($subscriptionCol) {
        return BookPub::DB::Item::Sale::kPurchaseTypeSubscriptionDL;
    } else {
        $self->fail("Unable to determine purchase type");
    }
}

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