package BookPub::Import::Importer::Izneo::v1;

use strict;
use warnings;

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

sub _fieldMap {
    {
        dateBegin              => 'L',
        priceType              => 'AK',
        rTitle                 => 'J',
        rIsbn13                => 'D',
        countryCode            => 'S',
        serviceProductID       => 'C',
        rUnits                 => 'AE',
        rListPrice             => 'T',
        rListPriceCurrency     => 'U',
        rPurchasePrice         => 'X',
        rPurchasePriceCurrency => 'AA',
        rDiscount              => 'AQ',
        rRevenue               => 'V',
        currencyCode           => 'W',
        isFree                 => 'AI',
        rDeliveryMethod        => 'N',
        rChannel               => 'P',
        rTransactionCategory   => 'AI',
    };
}

sub _headerIdentifier { rTitle => 'Titre' }

sub rServiceName               { 'Izneo' }
sub priceType                  { shift->rPriceType }
sub productType                { BookPub::DB::Item::Sale::kProductTypeEBook }
sub rProductType               { shift->productType() }
sub purchaseType               { BookPub::DB::Item::Sale::kPurchaseTypeDownload }
sub _useIsSaleRec              { 1 }

sub dateBegin {
    my $self = shift;

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

    # YYMM
    if ( $date =~ /^(\d\d)(\d\d)$/ ) {
        return sprintf "20%02d-%02d-%02d", $1, $2, 1;
    }

    $self->fail("Unable to determine date begin.");
}

sub rPriceType {
    my $self = shift;

    my $code = $self->_getByFieldName('countryCode') || '';
    return 'agency' if ( $code =~ /^US|CA$/ );
    return 'rrp' if $code;

    $self->fail("Unexpected country code for Price Type: $code ");
}

sub isFree {
    my $self  = shift;
    my $free = $self->_getByFieldName('isFree');

    return ($free =~ /^GRATUIT$/i) ? 'Y' : 'N';
}

sub _isSaleRec {
    my $self = shift;

    my $isbn   = $self->_getByFieldName('rIsbn13');
    my $title  = $self->_getByFieldName('rTitle');

    return 0 unless $isbn && $title;

    return $self->SUPER::_isSaleRec();
}

1;
