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

use strict;

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

sub _headerIdentifier { ( rTitle => 'Titre' ) }
sub _useIsSaleRec     { 1 }
sub priceType         { 'agency' }
sub purchaseType      { BookPub::DB::Item::Sale::kPurchaseTypeDownload }
sub productType       { BookPub::DB::Item::Sale::kProductTypeEBook }
sub countryCode       { 'FR' }
sub _dateNormalization { 'month' }

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 _processHeader {
    my $self   = shift;
    my $header = $self->_getByFieldName('rListPrice');

    if ( $header =~ m/EUROS/i ) {
        $self->{_currencyCode} = 'EUR';
    } else {
        $self->fail("Unexpected currency code encountered: $header");
    }
    return $self->SUPER::_processHeader(@_);
}

sub currencyCode           { shift->{_currencyCode} }
sub rListPriceCurrency     { shift->{_currencyCode} }
sub rPurchasePriceCurrency { shift->{_currencyCode} }

sub _getDateBegin { shift->{_dateBegin} }
sub _getDateEnd   { shift->_getDateBegin() }

sub _isSaleRec {
    my $self = shift;

    return $self->rTitle;
}

sub rImprint {
    my $self = shift;

    my $imprint = $self->SUPER::rImprint;

    # it's only reported for the first title, so we cache it
    if ($imprint) {
        $self->{_imprint} = $imprint;
    }

    return $self->{_imprint};
}

sub rAuthor {
    my $self = shift;

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

sub rTaxAmount {
    my $self          = shift;
    my $purchasePrice = $self->_getByFieldName('rPurchasePrice');
    my $revenue       = $self->_getByFieldName('rRevenue');

    return $purchasePrice - $revenue;
}

sub rPurchasePrice {
    my $self = shift;

    my $rPurchasePrice = 0;
    if ( $self->units ) {
        $rPurchasePrice = Common::RSMath::round( $self->SUPER::rPurchasePrice / $self->units, 2 );
    }

    return $rPurchasePrice;
}

sub rRevenue {
    my $self = shift;

    # i'd like to round here, but if we do it throws off revenue, guess we just have to
    # live with fractional pennies (or euro pennies or whatever)
    return $self->SUPER::rRevenue * .70;
}

1;
