package BookPub::Import::Importer::Audible::Version4;

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 { ( serviceProductID => 'Parent Product Id' ) }

sub _fieldMap {
    {
        serviceProductID => 'D',
        countryCode      => 'C',
        isbn             => 'G',
        rTitle           => 'E',
        rAuthor          => 'F',
        rUnits           => 'Q',
        rDiscount        => 'B',
        rRevenue         => 'S',
    };
}

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

sub _isValidSaleRecord {
    my $self = shift;

    # Ignore refunds with 0 revenue for Hachette only.
    return if ( !$self->rRevenue() && $self->rUnits() < 0 && Common::RSApp::GetClientID == 308 );

    return
         defined( $self->rTitle )
      && defined( $self->rRevenue )
      && defined( $self->serviceProductID )
      && $self->serviceProductID !~ /Total by/i;
}

sub _processHeader {
    my $self = shift;

    unless ( $self->_getDateBegin() ) {
        unless ( $self->filename =~ /(Q[1234])[_\s](\d{4})/ ) {
            $self->fail( "Unable to determine date from filename: " . $self->filename );
        }

        $self->{_dateBegin} = lc("$2$1");
    }
}

sub _dateFormat { [ 'quarter', 'iso' ] }
sub _dateNormalization { 'quarter' }
sub _getDateBegin      { shift->{_dateBegin} }

1;
