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

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 {

    # Starting with version 8
    {
        # detail
        rTitle       => 'A',
        rIsbn13      => 'C',
        rProductType => 'D',
        rImprint     => 'F',
        rListPrice   => 'G',
        rSales       => 'I',
        rReturns     => 'K',
        rUnits       => 'M',
        rRevenue     => 'N',
    };
}

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

sub _useIsSaleRec      { 1 }
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 dateTab            { 'Summary' }

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

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

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

        if ( $sheetname =~ /$dateTab/i ) {
            foreach my $line (@$sheet) {
                my $date = $line->[0];
                if ( $date =~ /^Total Due for (\w+) (20\d{2}):$/ ) {
                    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 _isSaleRec {
    my $self = shift;

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

1;

