package BookPub::Import::Importer::Lix::v1;

use strict;
use warnings;

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

use constant RE_YEAR_MONTH_DAY => qr/^(\d{4}).(\d{1,2}).(\d{1,2}).+$/;

sub _fieldMap {
    # SERVICE: 217, VERSION: 1
    {
        dateBegin              => 'E',
        dateEnd                => 'E',
        rAuthor                => 'D',
        rTitle                 => 'C',
        rIsbn13                => 'B',
        countryCode            => 'H',
        rUnits                 => 'G',
        rListPrice             => 'F',
        rListPriceCurrency     => 'I',
        rPurchasePrice         => 'L',
        rPurchasePriceCurrency => 'I',
        rCOGS                  => 'J',
        rRevenue               => 'M',
        currencyCode           => 'I',
    };
}

sub _headerIdentifier    { rIsbn13 => 'eISBN' }
sub _useIsSaleRec        { 1 }
sub priceType            { 'rrp' }
sub purchaseType         { BookPub::DB::Item::Sale::kPurchaseTypeDownload }
sub productType          { BookPub::DB::Item::Sale::kProductTypeEBook }
sub rProductType         { BookPub::DB::Item::Sale::kProductTypeEBook }

sub rServiceName {
    return BookPub::Tracker::Service::GetDefaultServiceName(
        service_id => shift->serviceID
    );
}

sub isFree {
    my $self = shift;

    my $match = '0.00';
    my $rListPrice     = $self->_getByFieldName('rPurchasePrice') || $match;
    my $rPurchasePrice = $self->_getByFieldName('rRevenue')       || $match;

    if ( $rListPrice eq $match && $rPurchasePrice eq $match ) {
        return 'Y';
    }

    return 'N';
}

sub dateBegin {
    my $self = shift;

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

    if ( my ($year, $month, $day) = $dateBegin =~ RE_YEAR_MONTH_DAY ) {
        return sprintf "%04d-%02d-%02d", $year, $month, $day;
    }

    $self->fail("Can't determine date: $dateBegin");
}

sub dateEnd { shift->dateBegin }

sub _isSaleRec {
    my $self = shift;

    return if $self->{_endOfData};

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

    return 1;
}


1;