package BookPub::Import::Importer::Numilog::Version5;

use strict;
use warnings;

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

sub _fieldMap {
    {
        rFormat                  => 'I',
        rTitle                   => 'C',
        rIsbn13                  => 'H',
        rInstitution             => 'X',
        countryCode              => 'P',
        rUnits                   => 'J',
        rUnitPrice               => 'Q',
        rListPrice               => 'R',
        rListPriceCurrency       => 'R',
        rNativeListPrice         => 'M',
        rNativeListPriceCurrency => 'O',
        rPurchasePrice           => 'K',
        rPurchasePriceCurrency   => 'O',
        rDiscount                => 'S',
        rRevenue                 => 'U',
        currencyCode             => 'R',
        rChannel                 => 'W',
        rModel                   => 'V',
        rComments                => 'Y',
    };
}

sub _unverifiedFieldMap {
    {
        publisher       => 'A',
        authorLastName  => 'E',
        authorFirstName => 'F',
    };
}

sub _headerIdentifier { rTitle => 'Title' }

sub _useIsSaleRec      { 1 }
sub rServiceName       { 'Numilog' }
sub currencyCode       { 'EUR' }
sub priceType          { 'agency' }
sub purchaseType       { BookPub::DB::Item::Sale::kPurchaseTypeDownload }
sub rPurchaseType      { BookPub::DB::Item::Sale::kPurchaseTypeDownload }
sub productType        { BookPub::DB::Item::Sale::kProductTypeEBook }
sub rProductType       { BookPub::DB::Item::Sale::kProductTypeEBook }
sub _getDateBegin      { shift->{_dateBegin} }
sub _getDateEnd        { shift->_getDateBegin() }
sub rListPriceCurrency { shift->currencyCode }

sub _preProcess {
    my $self = shift;
    my %args = @_;

    $self->SUPER::_preProcess(%args);

    my ( $month, $year ) = $self->filename =~ /^IV\d+_?M(\d+)_(\d{4})\./;
    $self->{_dateBegin} = sprintf( '%04d-%02d-01', $year, $month );
}

sub rAuthor {
    my $self = shift;

    return join( ' ',
        $self->_getByFieldName('authorFirstName'),
        $self->_getByFieldName('authorLastName')
    );
}

sub countryCode {
    my $self = shift;

    my $countryCode = $self->_getByFieldName('countryCode') || '';

    $self->fail("Unable to determine country code from: '$countryCode'") unless $countryCode;
    return $countryCode;
}

sub isFree {
    my $self = shift;

    return !$self->rRevenue && $self->rUnits ? 'Y' : 'N';
}

sub _isSaleRec {
    my $self = shift;

    $self->SUPER::_isSaleRec();

    my $publisher = $self->_getByFieldName('publisher') || '';

    if ( $publisher =~ /Total/i ) {
        $self->{_end_of_data} = 1;
    }

    return $self->{_end_of_data} ? 0 : 1;
}

1;
