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

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 {
    {
        # header
        dateBegin => 'H',

        # detail
        rProductType => 'D',
        isbn         => 'C',
        rTitle       => 'A',
        rUnits       => 'I',
        rListPrice   => 'G',
        rRevenue     => 'K',
    };
}

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 _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 =~ /downloadable/i ) {
            foreach my $line (@$sheet) {
                my $date = $line->[7];
                if ( $date =~ /(\d{1,2})\/(\d{2})$/ ) {
                    my $year  = "20" . $2;
                    my $month = $1;
                    my $day   = 1;
                    $self->{_dateBegin} = sprintf( "%04d-%02d-%02d", $year, $month, $day );
                }
                last;
            }
        }
    }
}

sub _getDateBegin { shift->{_dateBegin} }

sub _isValidSaleRecord {
    my $self             = shift;
    my $productType      = $self->rProductType;
    my $validProductType = 0;

    # We only want to process these two product types.
    if ( $productType =~ /^SL Dig Audiobk/i || $productType =~ /^HACD DigAudiobk/i ) {
        $validProductType = 1;
    }

    # We also only want to process the digital sales tab.
    return
         $self->sheetname
      && $self->sheetname =~ /downloadable/i
      && $validProductType;
}

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

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

    return ( $title, $1 );
}

1;
