package BookPub::Import::Importer::BarnesNoble::Version13;

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                 => 'AD',
        rPostalCode            => 'AE',
        dateBegin              => 'J',
        rIsbn13                => 'C',
        rTitle                 => 'D',
        rAuthor                => 'E',
        rUnits                 => 'U',
        rSales                 => 'I',
        rReturns               => 'I',
        rListPrice             => 'Q',
        rListPriceCurrency     => 'P',
        rPurchasePrice         => 'R',
        rPurchasePriceCurrency => 'P',
        rTaxAmount             => 'S',
        rDiscount              => 'V',
        rUnitPrice             => 'Z',
        rRevenue               => 'AA',
        rInstitution           => 'AI',
    };
}

sub _unverifiedFieldMap {
    {
        unitCostSaleCurrency => 'W',
        eGiftDateBegin       => 'J',
        orderType            => 'I',
    };
}

sub _useIsSaleRec { 1 }

# the base class does some stuff in this method that we don't want to do
sub preProcessLine { }

sub rSales {
    my $self      = shift;
    my $orderType = $self->_getByFieldName('orderType');
    my $units     = $self->_getByFieldName('rUnits');

    return $orderType eq 'INV' ? $units : 0;
}

sub rReturns {
    my $self      = shift;
    my $orderType = $self->_getByFieldName('orderType');
    my $units     = $self->_getByFieldName('rUnits');

    return $orderType eq 'CRE' ? abs($units) : 0;
}

sub rUnits {
    my $self    = shift;
    my $sales   = $self->rSales();
    my $returns = $self->rReturns();

    return $sales - $returns;
}

sub rRevenue {
    my $self    = shift;
    my $revenue = $self->_getByFieldName('rRevenue');

    return $revenue;
}

sub priceType {
    my $self = shift;
    my $priceType;
    my $fname = $self->filename();

    if ( $self->isMacmillan ) {
        my $country = $self->countryCode;
        if ( $fname =~ /_Int_/ ) {
            $priceType = 'rrp';
        } else {
            $priceType = 'agency';
        }
    } else {
        $priceType = 'rrp';
    }

    return $priceType;
}

sub _clientID       { return Common::RSApp::GetClientID() }
sub isMacmillan     { return ( Common::RSApp::GetClientID() == 318 ) ? 1 : 0 }
sub isWiley         { return ( Common::RSApp::GetClientID() == 324 ) ? 1 : 0 }
sub isBloomsburyUSA { return ( Common::RSApp::GetClientID() == 314 ) ? 1 : 0 }

sub rListPrice {
    my $self                 = shift;
    my $listPrice            = $self->_getByFieldName('rListPrice');
    my $unitPrice            = $self->_getByFieldName('rUnitPrice');
    my $currencyCode         = uc( $self->_getByFieldName('currencyCode') );
    my $listPriceCurrency    = uc( $self->_getByFieldName('rListPriceCurrency') );
    my $unitCostSaleCurrency = $self->_getByFieldName('unitCostSaleCurrency');

    # if currency and list price currency don't match, calculate the exchange rate
    # and apply it to the list price
    if ( $currencyCode ne $listPriceCurrency ) {
        if ( $unitCostSaleCurrency == 0 ) {
            $self->fail("Invalid Unit Sale Cost Currency of zero");
        } else {

            # derive exchangeRate
            my $rate = $unitPrice / $unitCostSaleCurrency;
            return $rate * $listPrice;
        }
    } else {
        return $listPrice;
    }
}

sub rListPriceCurrency {
    my $self = shift;

    # Since we are converting the list price to the revenue's currency,
    # we'll just grab that here instead.
    # We can't just map rListPriceCurrency to that column though,
    # because we need to be able to tell when we need to do the conversions.
    my $currencyCode = uc( $self->_getByFieldName('currencyCode') );

    return $currencyCode;
}

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 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 = ($postal->getName($rState) ? $rState : $postal->getAbbr($rState));

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

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

    return $state;
}

1;
