package BookPub::Import::Importer::txtr;

use strict;
use Spreadsheet::ParseExcel::Utility;

use lib '/app/tools/common/lib';
use Common::Util qw(trimleadingzeros);

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

my %priceTypeMap = (
    1  => 'rrp',
    2  => 'rrpplustax',
    41 => 'agency',
    42 => 'agencyplustax',
);

sub _fieldMap {
    {
        my $self = shift;

        my %fieldMap = (
            10 => {
                priceType              => 'AI',
                currencyCode           => 'N',
                countryCode            => 'X',
                dateBegin              => 'B',
                rProductType           => 'G',
                rIsbn13                => 'D',
                rTitle                 => 'F',
                rAuthor                => 'E',
                rListPrice             => 'I',
                rListPriceCurrency     => 'H',
                rPurchasePrice         => 'U',
                rPurchasePriceCurrency => 'U11',
                rDiscount              => 'AH',
                rRevenue               => 'P',
            },
            11 => {
                priceType          => 'AH',
                currencyCode       => 'P',
                countryCode        => 'X',
                rState             => 'AJ',
                rPostalCode        => 'AL',
                dateBegin          => 'C',
                rIsbn13            => 'E',
                rTitle             => 'F',
                rListPrice         => 'H',
                rListPriceCurrency => 'G',
                rDiscount          => 'AG',
                rRevenue           => 'O',
            },
            12 => {
                priceType          => 'AH',
                currencyCode       => 'N',
                countryCode        => 'W',
                dateBegin          => 'B',
                rFormat            => 'G',
                rIsbn13            => 'D',
                rTitle             => 'F',
                rAuthor            => 'E',
                rListPrice         => 'I',
                rListPriceCurrency => 'H',
                rDiscount          => 'AG',
                rRevenue           => 'P',
            },
            13 => {
                priceType          => 'AF',
                currencyCode       => 'P',
                conversionRate     => 'N',
                countryCode        => 'AH',
                rState             => 'AI',
                rPostalCode        => 'AK',
                dateBegin          => 'C',
                rIsbn13            => 'E',
                rTitle             => 'F',
                rListPrice         => 'H',
                rListPriceCurrency => 'G',
                rTaxAmount         => 'AS',
                rDiscount          => 'AE',
                rRevenue           => 'O',
            },
            14 => {
                priceType          => 'AE',
                currencyCode       => 'P',
                conversionRate     => 'N',
                countryCode        => 'AG',
                rState             => 'AH',
                rPostalCode        => 'AJ',
                dateBegin          => 'C',
                rIsbn13            => 'E',
                rTitle             => 'F',
                rListPrice         => 'H',
                rListPriceCurrency => 'G',
                rTaxAmount         => 'AR',
                rDiscount          => 'AD',
                rRevenue           => 'O',
            },
        );

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

sub _unverifiedFieldMap {
    my $self = shift;

    my %fieldMap = (
        10 => {
            exchangeRate => 'O',
            netPrice     => 'W',
            grossPrice   => 'U',
        },
    );

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

sub _headerIdentifier { ( rTitle => 'Title' ) }
sub _autoParseTitleAndSubtitle { 1 }
sub _useIsSaleRec              { 1 }
sub _dateFormat                { [ 'excel', 'iso' ] }

sub purchaseType { BookPub::DB::Item::Sale::kPurchaseTypeDownload }
sub productType  { BookPub::DB::Item::Sale::kProductTypeEBook }
sub units        { return ( shift->rRevenue >= 0 ) ? 1 : -1 }
sub isFree       { return ( shift->rRevenue == 0 ) ? 'Y' : 'N' }

sub priceType {
    my $self = shift;
    my $type = $self->_getByFieldName('priceType') || return;
    $type = trimleadingzeros($type);

    $self->fail("Unknown price type '$type'") unless exists $priceTypeMap{$type};

    return $priceTypeMap{$type};
}

sub rTaxAmount {
    my $self = shift;

    # We can't key off of anything in the unverified fieldmap, so we're stuck using
    # 'rPurchasePriceCurrency' to determine that this is version 10.
    if ( defined $self->_getByFieldName('rPurchasePriceCurrency') ) {
        my $grossPrice   = $self->_getByFieldName('grossPrice');
        my $netPrice     = $self->_getByFieldName('netPrice');
        my $exchangeRate = $self->_getByFieldName('exchangeRate');
        my $tax          = abs( ( $grossPrice - $netPrice ) / $exchangeRate );
        if ( $self->revenue() < 0 ) {
            $tax *= -1;
        }
        return $tax;
    } else {

        # Default behavior for everybody else.
        return $self->_getByFieldName('rTaxAmount');
    }
}

sub rPurchasePriceCurrency {
    my $self = shift;
    if ( defined $self->_getByFieldName('rPurchasePriceCurrency') ) {
        my $ppc = $self->_getByFieldName('rPurchasePriceCurrency');
        if ( $ppc =~ /in (\w{3})$/i ) {
            return $1;
        } else {
            $self->fail("Unable to find currency code in '$ppc'");
        }
    }
}

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

    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');

    if ( $self->listPriceRequired && $listPriceCurrency && $listPriceCurrency ne $revenueCurrency && $listPrice != 0 ) {
        $listPrice =~ s/,//g;
        my $conversionRate = $self->rRevenue / ( $listPrice * ( 1 - $self->rDiscount ) );
        $listPrice *= $conversionRate;
    }

    return abs($listPrice);
}

1;
