package BookPub::Import::Importer::SimplyAudio::Version2;

use strict;

use lib '/app/tools/common/lib';
use Common::Country;

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

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

sub _fieldMap {
    {
        rIsbn13    => 'A',
        rTitle     => 'B',
        rListPrice => 'D',
        rUnits     => 'F',
        rDiscount  => 'G',
        rRevenue   => 'H',
    };
}

sub _unverifiedFieldMap {
    { date => 'A', };
}

sub priceType    { 'rrp' }
sub purchaseType { BookPub::DB::Item::Sale::kPurchaseTypeDownload }
sub productType  { BookPub::DB::Item::Sale::kProductTypeAudioBook }

sub currencyCode { 'USD' }
sub countryCode  { 'US' }

# We have to read through the sheets before we process sales to find the dates
# on the summary page.
sub _importLines {
    my $self        = shift;
    my %args        = @_;
    my $sheetNumber = 0;

    foreach my $sheet ( @{ $args{sheets} } ) {
        if ( $args{sheet_names}->[$sheetNumber] =~ /Summary/i ) {
            $self->_saveDate($sheet);
        }

        $sheetNumber++;
    }

    unless ( $self->date ) {
        $self->fail("Failed to read dates from 'Summary' tab");
    }

    return $self->SUPER::_importLines(@_);
}

sub _getDateBegin {
    my $self = shift;
    return $self->date();
}

sub _getDateEnd {
    shift->_getDateBegin();
}

sub _dateNormalization { 'month' }

sub _saveDate {
    my $self = shift;
    my $sheet = shift || return;

    my $date;

    $self->{_date} = {};

    foreach my $line (@$sheet) {
        $self->{line} = $line;
        $date = $self->_getByFieldName('date');

        if ( $date && $date =~ /^(\d+\/\d+\/\d+)/ ) {
            $self->{_date} = $1;
        }
    }

    return unless ( $self->date );

    return $self->date();
}

sub date { shift->{_date} }

sub rIsbn13 {
    my $isbn = shift->SUPER::rIsbn13();
    $isbn =~ s/D?_D// if ($isbn);

    return $isbn;
}

1;
