package BookPub::Import::Importer::EBook::Version17;

use strict;

use Data::Dumper;
use POSIX;

use lib '/app/tools/common/lib';

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

sub _headerIdentifier { ( rTitle => 'Title' ) }

sub formatType    { BookPub::DB::Item::Sale::kFormatTypeEBL }
sub productType   { BookPub::DB::Item::Sale::kProductTypeEBook }
sub priceType     { 'rrp' }
sub _useIsSaleRec { 1 }

sub _fieldMap {
    {
        purchaseType       => 'J',
        currencyCode       => 'M',
        countryCode        => 'P',
        dateBegin          => 'I',
        isbn               => 'G',
        rTitle             => 'D',
        rImprint           => 'C',
        rUnits             => 'R',
        rListPrice         => 'Q',
        rListPriceCurrency => 'M',
        rDiscount          => 'U',
        rRevenue           => 'V',
    };
}

sub _isSaleRec {
    my $self = shift;

    my $dateBegin = $self->_getByFieldName('dateBegin');
    my $isbn      = $self->_getByFieldName('isbn');
    my $title     = $self->_getByFieldName('rTitle');
    my $units     = $self->_getByFieldName('rUnits');

    # We're going to skip the subtotal lines, which are blank for these fields
    if ( !$dateBegin && !$isbn && !$title && !$units ) {
        return 0;
    }

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

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

    if ( lc($purchaseType) eq 'stl' ) {
        return BookPub::DB::Item::Sale::kPurchaseTypeLoan;
    } elsif ( lc($purchaseType) eq 'non-linear lending' ) {
        return BookPub::DB::Item::Sale::kPurchaseTypeDownload;
    } elsif ( lc($purchaseType) eq 'unlimited' ) {
        return BookPub::DB::Item::Sale::kPurchaseTypeDownload;
    } elsif ( lc($purchaseType) eq 'chapter' ) {
        return BookPub::DB::Item::Sale::kPurchaseTypeDownload;
    } elsif ($purchaseType) {
        $self->fail("Unknown purchase type '$purchaseType'");
    }
}

sub _dateFormat { [ 'numerical_year_first', 'iso' ] }

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

    # Round up fractional units
    $units = ceil($units);

    if ( $revenue < 0 && $units > 0 ) {
        $units *= -1;
    }
    return $units;
}

1;
