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

use strict;
use Data::Dumper;

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

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

sub _fieldMap {
    {
        isbn           => 'G',
        rTitle         => 'E',
        rAuthor        => 'F',
        rUnits         => 'H',
        rListPrice     => 'I',
        rPurchasePrice => 'M',
        rDiscount      => 'N',

        #rRevenue              => 'O',
    };
}

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 _preProcess {
    my $self = shift;
    my %args = @_;

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

    foreach my $sheet ( @{ $args{sheets} } ) {
        foreach my $line (@$sheet) {

            # Since we're at the preProcess stage, it seems we have to reference rows by number.
            my $dateCell = $line->[3];
            if ( $dateCell =~ m/^(\w+ \d{4}) SALES REPORT - /i ) {
                $self->{_dateBegin} = "$1";
                last;
            }
        }

        # If we can't find the date 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 rDiscount {
    my $self = shift;

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

    return $discount;
}

sub rRevenue {
    my $self = shift;

    # The subtotal in the file is based on adding together the unrounded revenue for each
    # line, so we need to do the math.
    my $listPrice = $self->SUPER::rListPrice();
    my $units     = $self->SUPER::rUnits();
    my $discount  = $self->SUPER::rDiscount();

    my $revenue = $listPrice * $units * $discount;

    return $revenue;
}

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