package BookPub::Import::Importer::Perlego::Version5;

use strict;
use warnings;

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

sub _fieldMap {
    my $self = shift;

    my %map = (
        5 => {
            dateBegin          => 'D',
            dateEnd            => 'D',
            rFormat            => 'I',
            rAuthor            => 'G',
            rTitle             => 'F',
            rIsbn13            => 'E',
            rImprint           => 'L',
            rInstitution       => 'P',
            countryCode        => 'R',
            rUnitPrice         => 'M',
            rListPrice         => 'M',
            rListPriceCurrency => 'N',
            rRevenue           => 'M',
            currencyCode       => 'N',
            rChannel           => 'O',
        },
        7 => {
            dateBegin          => 'D',
            dateEnd            => 'D',
            rFormat            => 'I',
            rAuthor            => 'G',
            rTitle             => 'F',
            rIsbn13            => 'E',
            rImprint           => 'L',
            rInstitution       => 'T',
            countryCode        => 'V',
            rUnitPrice         => 'P',
            rListPrice         => 'N',
            rListPriceCurrency => 'O',
            rRevenue           => 'Q',
            currencyCode       => 'R',
            rChannel           => 'S',
        },
    );

    return $map{ $self->_version };
}

sub _headerIdentifier { rRevenue => 'Total Net Payment Amount' }

my %months = (
    jan => 1, feb => 2, mar => 3, apr => 4, may => 5, jun => 6,
    jul => 7, aug => 8, sep => 9, oct => 10, nov => 11, dec => 12
);

sub _useIsSaleRec { 1 }
sub rServiceName  { 'Perlego' }
sub priceType     { 'rrp' }
sub purchaseType  { BookPub::DB::Item::Sale::kPurchaseTypeSubscriptionDL }
sub productType   { BookPub::DB::Item::Sale::kProductTypeEBook }
sub rProductType  { BookPub::DB::Item::Sale::kProductTypeEBook }

sub dateBegin {
    my $self = shift;

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

    # d-mmm-yy
    if ( my($d, $m, $y) = $date =~ /^(\d{1,2})\-(\w{3,9})\-(\d{2,4})$/i ) {
        $m = lc( substr($m, 0, 3) );
        $m = $months{$m};
        $y = substr($y, -2);
        return sprintf "20%02d-%02d-%02d", $y, $m, $d;
    }

    $self->fail("Unable to determine date begin from: '$date'");
}

sub dateEnd { shift->dateBegin }

sub rRevenue {
    my $self = shift;

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

    return $rRevenue * 1;
}

sub rUnits {
    my $self = shift;

    return $self->rRevenue < 0 ? -1 : 1;
}

sub isFree {
    my $self = shift;

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

sub _isSaleRec {
    my $self = shift;

    return if $self->{_endOfData};

    unless ( $self->SUPER::_isSaleRec ) {
        $self->{_endOfData} = 1;
        return;
    }

    return 1;
}

1;