package BookPub::Import::Importer::Google::Version20;

use strict;
use Data::Dumper;

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

use lib '/app/tools/bookpub/lib';
use base 'BookPub::Import::Importer::Google::Version16';

sub _fieldMap {
    {
        isPreOrder         => 'F',
        currencyCode       => 'S',
        conversionRate     => 'U',
        countryCode        => 'P',
        dateBegin          => 'B',
        rIsbn13            => 'J',    # Labeled 'Secondary ISBN'
        rTitle             => 'L',
        rAuthor            => 'M',
        rImprint           => 'K',
        rUnits             => 'H',
        rSales             => 'E',
        rReturns           => 'E',
        rListPrice         => 'O',
        rListPriceCurrency => 'N',
        rDiscount          => 'Q',
        rRevenue           => 'T',
    };
}

sub priceType { 'rrp' }

sub _unverifiedFieldMap {
    {
        eIsbn              => 'I',    # Labeled 'Primary ISBN'
        unconvertedRevenue => 'R',
    };
}

sub _dateFormat { [ 'excel', 'iso', 'us', 'eur' ] }

sub _useIsSaleRec { 1 }

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

    return $revenue;
}

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

    # For Macmillan and RLPG, we're going to set the currency code to the revenue currency.
    # We'll also be converting the list pricewith 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->_getByFieldName('currencyCode');

    # For Macmillan and RLPG, we're going to convert the list price to the revenue currency with the conversion rate
    #
    if ( $self->listPriceRequired && $listPriceCurrency && $listPriceCurrency ne $revenueCurrency && $listPrice != 0 ) {
        $listPrice =~ s/,//g;

        my $conversionRate = $self->_getByFieldName('conversionRate');
        if ($conversionRate) {
            $listPrice *= $conversionRate;
        } else {

            # If the conversion rate is missing, let's try to take our best guess.
            my $revenue = $self->_getByFieldName('rRevenue');
            $revenue =~ s/,//g;
            my $foreignRevenue = $self->_getByFieldName('unconvertedRevenue');
            $foreignRevenue =~ s/,//g;
            if ($foreignRevenue) {
                $conversionRate = $revenue / $foreignRevenue;
                $listPrice *= $conversionRate;
            }
        }
    }

    return $listPrice;
}

###
1;    # Play nicely.
###
