package BookPub::Import::Importer::BookOfTheMonth::v1;

use strict;
use warnings;

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

use Date::Calc qw( Add_Delta_YM Days_in_Month);

sub _fieldMap {
    {
        dateBegin     => 'A',
        rPurchaseType => 'J',
        rProductType  => 'E',
        rAuthor       => 'D',
        rTitle        => 'C',
        rIsbn13       => 'E',
        countryCode   => 'I',
        rUnits        => 'G',
        rUnitPrice    => 'J',
        rListPrice    => 'F',
        rDiscount     => 'K',
        rRevenue      => 'H',
    };
}

sub _unverifiedFieldMap {{}}
sub _headerIdentifier { rTitle => 'Audiobook Title' }


sub rServiceName       { 'Book of the Month' }
sub _useIsSaleRec      { 1 }
sub purchaseType       { $_[0]->rPurchaseType() }
sub productType        { $_[0]->rProductType() }
sub currencyCode       { 'USD' }
sub rListPriceCurrency { 'USD' }
sub rPriceType         { 'rrp' }
sub priceType          { 'rrp' }


sub dateBegin {
    my $self = shift;

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

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

sub dateEnd {
    my $self = shift;

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

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

sub rProductType {
    my $self = shift;
    my $type = $self->_getByFieldName("rProductType") || "";
    return BookPub::DB::Item::Sale::kProductTypeAudioBook if $type;

    $self->fail("Unable to determine product type because the ISBN value is missing");
}

sub rPurchaseType {
    my $self = shift;
    my $type = $self->_getByFieldName("rPurchaseType") || "";

    return BookPub::DB::Item::Sale::kPurchaseTypeSubscriptionDL if $type;

    $self->fail("Unable to determine purchase type from '$type'");
}

sub countryCode {
    my $self = shift;

    my $code = $self->_getByFieldName("countryCode") || "";
    return $code =~ s/\.//gr;
}

sub isFree {
    my $self = shift;

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

sub _isSaleRec {
    my $self = shift;

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

    return undef unless ($date && $self->rTitle);

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

1;
