package BookPub::Import::Importer::Audible::Version3;

use strict;

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

use lib '/app/tools/sale_import/lib/';
use Import::ValidationError;

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

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

sub _fieldMap {
    {
        # Summary Page
        dateBegin => 'B',

        # Detail Page
        countryCode => 'C',
        rIsbn13     => 'G',
        rTitle      => 'E',
        rAuthor     => 'F',
        rUnits      => 'Q',
        rListPrice  => 'H',
        rRevenue    => 'R',
    };
}

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

sub _isValidSaleRecord {
    my $self    = shift;
    my $type    = $self->_getByFieldName('recordType');
    my $country = $self->_getByFieldName('countryCode');

    # Only process sales on the 'non-promotional' or 'details' tab
    my $validTab;
    my $validTabNames = _validTabNames();
    foreach my $validTabName (@$validTabNames) {
        if ( $self->sheetname() =~ /$validTabName/i ) {
            $validTab = 1;
        }
    }
    return unless $validTab;

    # Ignore refunds with 0 revenue for Hachette only.  See case #13098 and case #17008
    return if ( $type && $type eq 'refund' && !$self->rRevenue() && Common::RSApp::GetClientID == 308 );

    # Ignore inline total lines
    return if ( $country && $country =~ /^Total/i );

    # Only process purchase lines
    return unless ( $type eq 'purchase' );

    return ( $self->rTitle || $self->rAuthor ) && $self->dateBegin;
}

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

sub currencyCode { 'USD' }

sub _processHeader {
    my $self = shift;
    unless ( $self->_getDateBegin() ) {
        my $input = $self->_getByFieldName('dateBegin');
        $self->{_dateBegin} = $input if ( $input =~ /^\d+$/ || $input =~ /^\w{3}-\d{2}$/ );
    }
}

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

    Log->info("Starting _preProcess");
    $self->SUPER::_preProcess(%args);

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

        my $validTabNames = _validTabNames();
        foreach my $validTabName (@$validTabNames) {
            if ( $sheetname =~ /$validTabName/i ) {
                $foundTab = 1;
            }
        }
    }

    if ( !$foundTab ) {
        $self->errstr('Unable to find tab with sales data');
        return undef;
    }

}

sub _validTabNames { [ 'Total Sales', 'Non-Promotional', 'Details' ] }
sub _dateFormat { [ 'excel', 'text' ] }
sub _dateNormalization { 'month' }
sub _getDateBegin      { shift->{_dateBegin} }
sub _getDateEnd        { shift->_getDateBegin() }

1;
