package BookPub::Import::Importer::BarnesNoble::Version12;

use strict;
use Data::Dumper;

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

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 = (
        12 => {
            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         => 'Q',
            rPurchasePriceCurrency => 'O',
            rTaxAmount             => 'R',
            rTransactionCategory   => 'H',
            rDiscount              => 'V',
            rUnitPrice             => 'W',
            rRevenue               => 'AA',
            rInstitution           => 'AI',
        },
    );

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

sub _unverifiedFieldMap {
    my $self = shift;

    my %fieldMap = (
        12 => {
            unitCostSaleCurrency => 'W',
            eGiftDateBegin       => 'J',
        },
    );

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

sub _useIsSaleRec { 1 }

sub priceType {
    my $self = shift;
    my $cID  = Common::RSApp::GetClientID();

    # For Macmillan US, we're going to set the price type to Agency.
    if ( $cID == 318 ) {

        # Unless it's the International file
        if ( $self->filename =~ /_Int_/ ) {
            return 'rrp';
        }
        return 'agency';
    }

    # Everyone else is RRP
    return 'rrp';
}

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

    my $code = $self->_getByFieldName('countryCode') || '';
    return 'US' if $code == 1;

    my $oCountry = Common::Country->Get($code) if $code;
    return $oCountry->alpha2() if $oCountry;

    $self->fail("Unknown country code '$code'");
}

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

    my $rState = $self->_getByFieldName('rState') || '';
    my $country = $self->_getByFieldName('countryCode') || '';

    return 'AA' if $rState =~ /^APO$/i;
    return 'AP' if $rState =~ /^FPO$/i;

    my $postal = Common::Postal->new( $self->countryCode() );

    my $state;
    if ( $postal ) {
        $state = $rState if $postal->getName($rState);
        $state = $postal->getAbbr($rState);
    }

    return undef if ($country =~ /^0*1$/ && !$state);

    $self->fail( "Invalid state '$rState' (country: " . $self->countryCode . ")" ) unless $state;

    return $state;
}

sub rListPriceCurrency {
    my $self              = shift;
    my $listPriceCurrency = $self->_getByFieldName('rListPriceCurrency');
    my $revenueCurrency   = $self->_getByFieldName('currencyCode');

    # For Macmillan, RLPG, and Wiley, we're going to set the list price currency to the revenue currency.
    # We'll also be converting the list price with the conversion rate.
    if ( $self->listPriceRequired && $listPriceCurrency && $listPriceCurrency ne $revenueCurrency ) {
        $listPriceCurrency = $revenueCurrency;
    }

    return $listPriceCurrency;
}

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

    # For client that require a list price, we'll convert it to be in the same currency as the revenue now.
    #
    if ( $self->listPriceRequired && $listPriceCurrency && $listPriceCurrency ne $revenueCurrency && $listPrice != 0 ) {
        my $unitCostSaleCurrency = $self->_getByFieldName('unitCostSaleCurrency');
        if ( $unitCostSaleCurrency == 0 ) {
            $self->fail("Invalid Unit Sale Cost Currency of zero");
        } else {

            # derive exchangeRate
            my $unitPrice = $self->_getByFieldName('rUnitPrice');
            my $rate      = $unitPrice / $unitCostSaleCurrency;
            $listPrice *= $rate;
        }
    }

    return $listPrice;
}

sub isFree {
    my $self = shift;

    return !$self->rRevenue && $self->rSales ? 'Y' : 'N';
}

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


1;
