package BookPub::Import::Importer::BarnesNoble::Version10;

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

sub _fieldMap {
    {
        currencyCode       => 'Y',
        countryCode        => 'L',
        rState             => 'AE',
        rPostalCode        => 'AF',
        dateBegin          => 'I',
        rIsbn13            => 'B',
        rTitle             => 'C',
        rAuthor            => 'D',
        rSales             => 'T',
        rReturns           => 'U',
        rListPrice         => 'P',
        rListPriceCurrency => 'AB',
        rPurchasePrice     => 'Q',
        rDiscount          => 'V',
        rUnitPrice         => 'Z',
        rRevenue           => 'AA',
    };
}

sub _unverifiedFieldMap {
    {
        totalCostSaleCurrency => 'X',
        eGiftDateBegin        => 'J',
        publisher             => 'E',
    };
}

sub _useIsSaleRec { 1 }

sub rListPriceCurrency {
    my $self     = shift;
    my $currency = $self->_getByFieldName('rListPriceCurrency');

    # For RLPG, we're going to set the currency code to USD.
    # We'll also be converting the list price to USD with the conversion rate
    if ( Common::RSApp::GetClientID == 346 ) {
        print STDERR "changing currency code to USD\n";
        $currency = 'USD';
    }

    return $currency;
}

sub rListPrice {
    my $self      = shift;
    my $listPrice = $self->_getByFieldName('rListPrice');
    my $currency  = $self->_getByFieldName('rListPriceCurrency');

    # For RLPG, we're going to convert the list price to USD with the conversion rate
    #
    if ( Common::RSApp::GetClientID == 346 && $currency ne 'USD' ) {
        $listPrice =~ s/,//g;
        my $unitPrice      = $self->_getByFieldName('rUnitPrice');
        my $totalCost      = $self->_getByFieldName('totalCostSaleCurrency');
        my $conversionRate = ( $unitPrice / $totalCost ) / $self->units();

        $listPrice *= $conversionRate;
    }

    return $listPrice;
}

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;
}

1;
