package BookPub::Import::Importer::Perlego::Version4;

use strict;
use warnings;

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

sub _fieldMap {
    {
        dateBegin          => 'B',
        dateEnd            => 'C',
        rIsbn13            => 'H',
        countryCode        => 'J',
        serviceProductID   => 'A',
        rUnits             => 'I',
        rListPrice         => 'E',
        rListPriceCurrency => 'E',
        rRevenue           => 'G',
        currencyCode       => 'G',
    }
}

sub _headerIdentifier { rRevenue => 'Royalty Value USD' }

sub _processHeader {
    my $self = shift;

    if ( $self->_isHeader() ) {
        my $currency = $self->_getByFieldName('currencyCode') || '';
        $self->{_currency_code} = 'USD' if $currency =~ /USD$/i;
    }

    return 1;
}

sub dateBegin {
    my $self = shift;

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

    # YYYY-MM-DD
    if ( $date =~ /^(\d{4})[-\/.](\d{1,2})[-\/.](\d{1,2})/ ) {
        return "$1-$2-$3";
    }

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

sub dateEnd {
    my $self = shift;

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

    # YYYY-MM-DD
    if ( $date =~ /^(\d{4})[-\/.](\d{1,2})[-\/.](\d{1,2})/ ) {
        return "$1-$2-$3";
    }

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

sub rListPrice {
    my $self = shift;

    my $rListPrice = $self->_getByFieldName('rListPrice') || 0;
    $rListPrice =~ s/[^0-9\.]//g;

    return $rListPrice;
}

sub rListPriceCurrency {
    my $self = shift;

    my $rListPriceCurrency = $self->_getByFieldName('rListPriceCurrency') || '';
    return 'GBP' if $rListPriceCurrency =~ /.?£/;

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

sub rRevenue {
    my $self = shift;

    my $rRevenue = $self->_getByFieldName('rRevenue') || 0;
    $rRevenue =~ s/[^0-9\.]//g;

    return $rRevenue;
}

sub isFree {
    my $self = shift;

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


1;