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

use strict;

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

sub _fieldMap {
    {
        priceType              => 'AM',
        currencyCode           => 'B5',
        countryCode            => 'AC',
        rState                 => 'AQ',
        rPostalCode            => 'AS',
        dateBegin              => 'B',
        isbn                   => 'D',
        rTitle                 => 'F',
        rAuthor                => 'E',
        rListPrice             => 'I',
        rListPriceCurrency     => 'H',
        rPurchasePrice         => 'Y',
        rPurchasePriceCurrency => 'Y11',
        rDiscount              => 'AL',
        rRevenue               => 'P',
    };
}

sub _unverifiedFieldMap {
    {
        netPrice     => 'AB',
        exchangeRate => 'O',
    };
}

sub _useIsSaleRec              { 1 }
sub _autoParseTitleAndSubtitle { 1 }
sub units                      { 1 }
sub _headerIdentifier          { ( rTitle => 'Title' ) }
sub purchaseType               { BookPub::DB::Item::Sale::kPurchaseTypeDownload }
sub productType                { BookPub::DB::Item::Sale::kProductTypeEBook }

sub rPurchasePriceCurrency {
    my $self                  = shift;
    my $purchasePriceCurrency = $self->_getByFieldName('rPurchasePriceCurrency');

    if ( $purchasePriceCurrency =~ / (\w{3})$/ ) {
        return $1;
    } else {
        $self->fail("Unable to find purchase price currency in header: $purchasePriceCurrency");
    }
}

sub rTaxUnitPrice {
    my $self          = shift;
    my $purchasePrice = $self->_getByFieldName('rPurchasePrice');
    my $netPrice      = $self->_getByFieldName('netPrice');
    my $exchangeRate  = $self->_getByFieldName('exchangeRate');

    my $tax = ( $purchasePrice - $netPrice ) / $exchangeRate;

    return $tax;
}

sub rAuthor {
    my $self   = shift;
    my $author = $self->_getByFieldName('rAuthor');

    if ( $author eq 'n/a' ) {
        return;
    }

    return $author;
}

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

    my $typeID =
        $type == 1  ? 'rrp'
      : $type == 2  ? 'rrpplustax'
      : $type == 41 ? 'agency'
      : $type == 42 ? 'agencyplustax'
      :               undef;

    $self->fail("Unknown price type '$type'") unless ($typeID);

    return $typeID;
}

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