package BookPub::Import::Importer::BarnesNoble::Version11;

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 {
    my $self = shift;

    my %fieldMap = (
        11 => {
            currencyCode           => 'Y',
            countryCode            => 'L',
            rState                 => 'AD',
            rPostalCode            => 'AE',
            dateBegin              => 'I',
            rIsbn13                => 'B',
            rTitle                 => 'C',
            rAuthor                => 'D',
            rSales                 => 'T',
            rReturns               => 'U',
            rListPrice             => 'P',
            rListPriceCurrency     => 'O',
            rPurchasePrice         => 'S',
            rPurchasePriceCurrency => 'O',
            rTaxAmount             => 'R',
            rDiscount              => 'V',
            rUnitPrice             => 'Z',
            rRevenue               => 'AA',
            rTransactionCategory   => 'H',
        },
    );

    return $fieldMap{ $self->_version() };
}

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

sub _useIsSaleRec { 1 }
sub _dateFormat { [ 'numerical_year_first', 'iso' ] }

sub _isSaleRec {
    my $self = shift;

    # Need to ignore the mostly blank summary line at the end of the file
    if (   !$self->_getByFieldName('currencyCode')
        && !$self->_getByFieldName('rTitle')
        && !$self->_getByFieldName('rAuthor')
        && !$self->_getByFieldName('countryCode')
        && !$self->_getByFieldName('rIsbn13')
        && !$self->_getByFieldName('rDiscount') ) {
        return undef;
    }

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

sub priceType {
    my $self = shift;

    # For Macmillan UK, we're going to set the price type to RRP.
    if ( Common::RSApp::GetClientID == 359 ) {
        return 'rrp';
    }

    # For Macmillan AU, we're going to set the price type to RRP.
    elsif ( Common::RSApp::GetClientID == 348 ) {
        return 'rrp';
    }

    return 'agency';
}

# if negative revenue, return a negative unit, otherwise a positive one
sub units {
    my $self = shift;
    my $rev  = $self->_getByFieldName('rRevenue');

    return $rev < 0 ? -1 : 1;
}

sub _getDateBegin {
    my $self = shift;

    # We'll use the eGift Date if that column is populated.
    my $date = $self->_getByFieldName('eGiftDateBegin');

    if ( !$date || $date eq '-' ) {
        $date = $self->_getByFieldName('dateBegin');
    }

    return $date;
}

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 rState {
    my $self  = shift;
    my $state = $self->SUPER::rState();

    if ( lc($state) eq '-' ) {
        return;
    }
    return $state;
}

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;
