package BookPub::Import::Importer::Gardners::Version15;

use strict;
use warnings;

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

use Common::RSMath;

use base 'BookPub::Import::Importer';

sub _fieldMap {
    {
        rServiceName             => 'A1',
        dateBegin                => 'A',
        rTitle                   => 'C',
        rIsbn13                  => 'B',
        countryCode              => 'D',
        rUnits                   => 'G',
        rListPrice               => 'I',
        rListPriceCurrency       => 'I4',
        rNativeListPrice         => 'H',
        rNativeListPriceCurrency => 'E',
        rDiscount                => 'H2',
        rRevenue                 => 'L',
        currencyCode             => 'I4',
        rDistributor             => 'F2',
    };
}

sub _headerIdentifier { rIsbn13 => 'EAN' }

sub _useIsSaleRec { 1 }
sub _isSaleRec   { shift->rIsbn13 }
sub priceType    { 'rrp' }
sub productType  { BookPub::DB::Item::Sale::kProductTypeEBook }
sub purchaseType { BookPub::DB::Item::Sale::kPurchaseTypeDownload }

sub rServiceName {
    my $self = shift;

    my $rServiceName = $self->_getByFieldName('rServiceName') || '';
    $rServiceName =~ s/^(\w+).*$/$1/;

    return $rServiceName;
}

sub _getDateBegin {
    my $self = shift;

    my ($fileMonth) = $self->filename =~ /(\d{2})20\d{2}/;

    my $dateBegin = $self->_getByFieldName('dateBegin') || '';
    if ( $dateBegin =~ /^(\d{1,2}).(\d{1,2}).(\d{4})$/ ) {
        return sprintf "%04d-%02d-%02d", $3, $2, $1;
    } elsif ( $dateBegin =~ /^(\d{4}).(\d{1,2}).(\d{1,2})$/ ) {
        return sprintf "%04d-%02d-%02d", $1, $2, $3;
    }

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

sub rUnitPrice {
    my $self = shift;

    return $self->rRevenue / $self->rUnits;
}

sub rListPriceCurrency {
    my $self = shift;

    my $rListPriceCurrency = $self->_getByFieldName('rListPriceCurrency') || '';
    $rListPriceCurrency =~ s/.*\((\w{3})\)$/$1/;

    return $rListPriceCurrency;
}

sub currencyCode {
    my $self = shift;

    my $currencyCode = $self->_getByFieldName('currencyCode') || '';
    $currencyCode =~ s/.*\((\w{3})\)$/$1/;

    return $currencyCode;
}

sub isFree {
    my $self = shift;

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


1;
