package BookPub::Import::Importer::Gardners::Version16;

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 {
    {
        dateBegin                => 'W',
        rFormat                  => 'B',
        rAuthor                  => 'D',
        rTitle                   => 'C',
        rIsbn13                  => 'A',
        countryCode              => 'Y',
        rUnits                   => 'O',
        rListPrice               => 'I',
        rListPriceCurrency       => 'N',
        rNativeListPrice         => 'R',
        rNativeListPriceCurrency => 'T',
        rRevenue                 => 'P',
        currencyCode             => 'N',
        rDistributor             => 'X',
    };
}

sub _headerIdentifier { rIsbn13 => 'ISBN13' }

sub _useIsSaleRec { 1 }
sub productType   { BookPub::DB::Item::Sale::kProductTypeEBook }
sub purchaseType  { BookPub::DB::Item::Sale::kPurchaseTypeDownload }
sub priceType     { 'rrp' }

sub rServiceName { 'Gardners' }

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 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';
}

sub _isSaleRec {
    my $self = shift;

    my $rIsbn13 = $self->rIsbn13;
    if ( !$rIsbn13 || $rIsbn13 =~ /^TOTAL.*?$/gi ) {
        return 0;
    }

    return 1;
}


1;