package BookPub::Import::Importer::BarnesNoble::Version9;

use strict;
use Data::Dumper;

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

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

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

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

sub _fieldMap {
    {
        currencyCode           => 'Y',
        countryCode            => 'M',
        rState                 => 'AE',
        rPostalCode            => 'AF',
        dateBegin              => 'J',
        rIsbn13                => 'C',
        rTitle                 => 'D',
        rAuthor                => 'E',
        rSales                 => 'U',
        rReturns               => 'U',
        rListPrice             => 'Q',
        rListPriceCurrency     => 'AB',
        rPurchasePrice         => 'R',
        rPurchasePriceCurrency => 'P',
        rTaxAmount             => 'S',
        rDiscount              => 'V',
        rUnitPrice             => 'Z',
        rRevenue               => 'AA',
    };
}

sub _useIsSaleRec { 1 }

sub postalCode {
    my $self = shift;

    my $postalCode;

    if ( my $rPostalCode = $self->rPostalCode() ) {
        if ( $rPostalCode =~ /^(\d{5})-$/ ) {
            $rPostalCode = $1;
        }

        if ( my $postal = Common::Postal->new( $self->countryCode() ) ) {
            $postalCode = $postal->formatPostalCode($rPostalCode);

            if ( !$postalCode ) {
                return;

                # Rather than throwing an error, we'll just leave out the invalid zip codes.
                #$self->fail("Invalid postal code '$rPostalCode'");
            }
        }
    }

    return $postalCode;
}

sub rTaxAmount {
    my $self = shift;

    my $tax     = $self->SUPER::rTaxAmount();
    my $revenue = $self->rRevenue();

    if ( $revenue > 0 ) {
        $tax = abs($tax);
    }

    if ( $revenue < 0 ) {
        $tax = abs($tax) * -1;
    }

    return $tax;
}

1;
