package BookPub::Import::Importer::BBCAudio::Version6;

use strict;

use lib '/app/tools/common/lib';
use Common::Assert;
use Data::Dumper;

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

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

sub _fieldMap {
    {
        # detail
        rIsbn10    => 'E',
        rIsbn13    => 'F',
        rTitle     => 'A',
        rImprint   => 'C',
        rUnits     => 'J',
        rListPrice => 'G',
        rRevenue   => 'R',
    };
}

sub _unverifiedFieldMap {
    { revenueBeforeDistFee => 'I', };
}

sub priceType          { 'rrp' }
sub purchaseType       { BookPub::DB::Item::Sale::kPurchaseTypeDownload }
sub formatType         { BookPub::DB::Item::Sale::kFormatTypeAudioUnknown }
sub productType        { BookPub::DB::Item::Sale::kProductTypeAudioBook }
sub countryCode        { 'US' }
sub currencyCode       { 'USD' }
sub _dateFormat        { 'text' }
sub _dateNormalization { 'month' }

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

    $self->SUPER::_preProcess(%args);

    my $sheetnum = 0;
    foreach my $sheet ( @{ $args{sheets} } ) {
        my $sheetname = $args{sheet_names}->[$sheetnum];
        $sheetnum++;

        if ( $sheetname =~ /digital/i ) {
            foreach my $line (@$sheet) {
                my $date = $line->[0];
                if ( $date =~ / (\w+) (\d{4})$/ ) {
                    my $year = $2;
                    my $month = substr( $1, 0, 3 );
                    $self->{_dateBegin} = $month . " " . $year;
                }
                last;
            }
        }
    }
}

sub _getDateBegin { shift->{_dateBegin} }
sub _getDateEnd   { shift->_getDateBegin() }

sub rPurchasePrice {
    my $self    = shift;
    my $units   = $self->_getByFieldName('rUnits');
    my $revenue = $self->_getByFieldName('revenueBeforeDistFee');
    my $purchasePrice;

    if ($units) {
        $purchasePrice = $revenue / $units;
    }

    return $purchasePrice;
}

sub _isValidSaleRecord {
    my $self = shift;

    # We only want to process the digital sales tab.
    if ( $self->sheetname && $self->sheetname =~ /digital/i ) {
        return $self->SUPER::_isValidSaleRecord();
    } else {
        return 0;
    }
}

1;
