package BookPub::Import::Importer::Fable::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 {
    {
        rServiceName       => 'DW',
        dateBegin          => 'P',
        dateEnd            => 'P',
        rProductType       => 'AE',
        rFormat            => 'AE',
        priceType          => 'I',
        rAuthor            => 'Z',
        rTitle             => 'Y',
        rIsbn13            => 'V',
        rImprint           => 'AD',
        rState             => 'BU',
        rPostalCode        => 'BY',
        countryCode        => 'L',
        rReturns           => 'AH',
        rSales             => 'AG',
        rUnits             => 'AI',
        rListPrice         => 'DY',
        rListPriceCurrency => 'AP',
        rDiscount          => 'AQ',
        rRevenue           => 'BD',
        currencyCode       => 'J',
        rTaxAmount         => 'DU',
        rTaxUnitPrice      => 'AN',
        isFree             => 'AJ',
    };
}

sub _unverifiedFieldMap {
    {
        skipHeaderMarker => 'A',
    }
}

sub _headerIdentifier { rIsbn13 => 'Main product ID#' }

sub _useIsSaleRec              { 1 }
sub _autoParseTitleAndSubtitle { 1 }
sub priceType                  { 'agency' }
sub purchaseType               { BookPub::DB::Item::Sale::kPurchaseTypeDownload }
sub rServiceName               { 'Fable' }

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 productType {
    my $self = shift;

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

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

sub rFormat {
    my $self = shift;

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

sub _isSaleRec {
    my $self = shift;

    # skip additional lines of the header
    my $header = $self->_getByFieldName('skipHeaderMarker') || '';
    if ( $header =~ /^(?:Usage:|Data type)/i ) {
        return;
    }

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

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

sub isFree {
    my $self = shift;

    my $isFree = $self->_getByFieldName('isFree') || '';
    return $isFree ? 'Y' : 'N';
}


1;
