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

use strict;

use Common::Assert;
use Data::Dumper;

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

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

sub _fieldMap {
    {
        dateBegin        => 'E',
        rClientProductID => 'B',
        rProductType     => 'D',
        isbn             => 'A',
        rTitle           => 'C',
        rUnits           => 'K',
        rListPrice       => 'N',
        rRevenue         => 'M',
    };
}

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

sub _getDateBegin {
    my $self = shift;
    my $date = $self->_getByFieldName('dateBegin') || return;

    # the date is being returned in the "days since 1/1/1900" format, so we need
    # to convert it.  We'll check if it's a 5 digit number and greater than the
    # number of days since 1/1/1900 on 1/1/2006, which is 38716
    if ( $date =~ /^\d{5}$/ and $date > 38716 ) {
        $date = Spreadsheet::ParseExcel::Utility::ExcelFmt( "yyyy-mm-dd", $date );
        return $date;
    }

    return $date

}

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

    if ( $args{sheet_names} && @{ $args{sheet_names} } > 1 ) {
        $self->{_splitFile} = 1;
    }

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

sub splitFile { shift->{_splitFile} }

sub _isValidSaleRecord {
    my $self = shift;

    # Some files are split into physical and digital tabs.  This is a problem
    # because the file also contained the consolidated report which has digital
    # sales re-reported.  So we need to test for that.
    if ( $self->splitFile() ) {
        return
             $self->sheetname
          && $self->sheetname =~ /digital/i
          && $self->SUPER::_isValidSaleRecord();
    } else {
        return
             $self->rProductType
          && $self->rProductType =~ /\bdig/i
          && $self->SUPER::_isValidSaleRecord();
    }

    return $self->SUPER::_isValidSaleRecord();
}

sub rTitle {
    my ( $title, $format ) = shift->_parseTitle();
    return $title;
}

sub rFormat {
    my ( $title, $format ) = shift->_parseTitle();
    return $format;
}

sub _parseTitle {
    my $title = shift->SUPER::rTitle() || return;
    $title =~ s/\s*\-\s*(libdig|mp3cd|ucd)\s*$//;

    return ( $title, $1 );
}

1;
