package BookPub::Import::Importer::Inkling;

use strict;

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

use Date::Calc qw( Add_Delta_YM );

sub _headerIdentifier { ( rIsbn13 => 'Inkling ISBN13' ) }

sub _fieldMap {
    my $self = shift;

    my %fieldMap = (
        1 => {
            currencyCode       => 'AA1',
            countryCode        => 'R',
            rState             => 'Q',
            dateBegin          => 'B',
            dateEnd            => 'C',
            rProductType       => 'N',
            rIsbn13            => 'G',
            rTitle             => 'L',
            rAuthor            => 'K',
            rImprint           => 'J',
            rUnits             => 'S',
            rFee               => 'X',
            rListPrice         => 'T',
            rListPriceCurrency => 'T1',
            rTaxAmount         => 'U',
            rRevenue           => 'AA',
            rInstitution       => 'P',
        },
    );

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

sub _unverifiedFieldMap {
    my $self = shift;

    # subtotal and unusedIsbn are used in isSaleRec
    my %fieldMap = (
        1 => {
            creditCardFee => 'W',
        },
    );

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

sub _useIsSaleRec              { 1 }
sub _autoParseTitleAndSubtitle { 1 }
sub priceType                  { 'rrp' }
sub purchaseType               { BookPub::DB::Item::Sale::kPurchaseTypeDownload }

sub productType {
    my $self = shift;

    my $type = $self->_getByFieldName('rProductType');
    if ( lc($type) eq 'book' ) {
        return BookPub::DB::Item::Sale::kProductTypeEBook;
    }
    if ( lc($type) eq 'chapter' ) {
        return BookPub::DB::Item::Sale::kProductTypeEBook;
    }

    $self->fail("Unknown product type: $type");
}

sub rFee {
    my $self = shift;

    my $fee   = $self->_getByFieldName('rFee');
    my $ccFee = $self->_getByFieldName('creditCardFee');

    return $fee + $ccFee;
}

sub rListPrice {
    my $self = shift;

    my $price = $self->_getByFieldName('rListPrice');
    my $units = $self->_getByFieldName('rUnits');

    return abs( $price / $units );
}

sub currencyCode {
    my $self = shift;

    my $currency = $self->_getByFieldName('currencyCode');

    if ( $currency =~ /\((\w{3})\)$/ ) {
        return $1;
    }

    $self->fail("Unable to find currency code in header");
}

sub rListPriceCurrency {
    my $self = shift;

    my $currency = $self->_getByFieldName('rListPriceCurrency');

    if ( $currency =~ /\((\w{3})\)$/ ) {
        return $1;
    }

    $self->fail("Unable to find list price currency in header");
}

sub _isSaleRec {
    my $self = shift;

    # We're going to check for the subtotal line
    my $country = $self->_getByFieldName('countryCode');
    if ( uc($country) eq 'TOTAL' ) {
        return 0;
    }

    return $self->SUPER::_isSaleRec();
}

1;
