package BookPub::Import::Importer::Chapter::v1;

use strict;
use warnings;


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          => 'B',
        dateEnd            => 'B',
        rProductType       => 'E',
        rTitle             => 'C',
        rIsbn13            => 'A',
        rUnits             => 'G',
        rListPrice         => 'F',
        rListPriceCurrency => 'I',
        rRevenue           => 'H',
        currencyCode       => 'I',
    };
}

sub _headerIdentifier { rIsbn13 => 'ISBN' }

sub rServiceName { 'Chapter' }
sub priceType    { 'rrp' }
sub countryCode  { 'DK' }
sub purchaseType { BookPub::DB::Item::Sale::kPurchaseTypeStream }

sub dateBegin {
    my $self = shift;

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

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

sub dateEnd {
    my $self = shift;

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

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

sub productType {
    my $self = shift;

    my $type = $self->_getByFieldName('rProductType') || '';
    if ( $type =~ /^audio$/i ) {
        return BookPub::DB::Item::Sale::kProductTypeAudioBook;
    }

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

sub isFree {
    my $self = shift;

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


1;
