package BookPub::Import::Importer::Audible::Version7;

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::Audible';

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

sub _isSaleRec {
    my $self = shift;
    my $id   = $self->_getByFieldName('serviceProductID');

    # skipping some sub-total lines
    if ( $id eq 'Total by Marketplace' || $id eq 'Grand Total' ) {
        return 0;
    }

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

sub countryCode {
    my $self = shift;
    my $code = $self->_getByFieldName('countryCode');
    if ($code) {
        $self->{_countryCode} = $code;
        return $code;
    } else {
        return $self->{_countryCode};
    }
}

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

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

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

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

sub units {

    # We need to make sure that the sign of the units matches the sign of the revenue
    my $self    = shift;
    my $units   = $self->_getByFieldName('rUnits');
    my $revenue = $self->rRevenue;

    if ( ( $revenue < 0 && $units > 0 ) || ( $revenue > 0 && $units < 0 ) ) {
        $units *= -1;
    }

    return $units;
}

###
1;    # Play nicely.
###
