package BookPub::Import::Importer::Blinkist::v2;

use strict;
use warnings;

use POSIX;

use lib '/app/tools/common/lib';
use Date::Calc qw(Days_in_Month);

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


sub _fieldMap {
    {
        dateBegin          => 'C',
        dateEnd            => 'C',
        rAuthor            => 'G',
        rTitle             => 'F',
        rIsbn13            => 'E',
        countryCode        => 'K',
        rUnits             => 'S',
        rListPrice         => 'J',
        rListPriceCurrency => 'D',
        rRevenue           => 'T',
        currencyCode       => 'D',
        rTaxAmount         => 'L',
    };
}

sub _headerIdentifier { rIsbn13 => 'record_reference' }

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

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

sub _getDateBegin {
    my $self = shift;

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

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

sub _getDateEnd {
    my $self = shift;

    my $date = $self->_getByFieldName('dateEnd') || '';
    if ( $date =~ /(\d{4})[\/-](\d{1,2})[\/-](\d{1,2})/i ) {
        return sprintf "%04d-%02d-%02d", $1, $2, $3;
    }

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

sub countryCode {
    my $self = shift;

    my $code = $self->_getByFieldName('countryCode') || '';
    return uc $code;
}

sub currencyCode {
    my $self = shift;

    my $code = $self->_getByFieldName('currencyCode') || '';
    return uc $code;
}

sub rListPriceCurrency {
    my $self = shift;

    my $listPriceCurrency = $self->_getByFieldName('rListPriceCurrency') || '';
    return uc $listPriceCurrency;
}

sub rRevenue {
    my $self = shift;

    my $revenue = $self->_getByFieldName('rRevenue') || 0;
    return $revenue;
}

sub rUnits {
    my $self = shift;

    my $units = $self->_getByFieldName('rUnits') || 0;
    return ceil($units);
}

sub _isSaleRec {
    my $self = shift;

    my $isbn = $self->_getByFieldName('rIsbn13') || '';
    return unless $isbn;

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


1;