package BookPub::Import::Importer::DeMarque::v3;

use strict;
use warnings;

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


sub _fieldMap {
    {
        dateBegin                => 'D',
        dateEnd                  => 'D',
        rPurchaseType            => 'F',
        rProductType             => 'AG',
        rFormat                  => 'AG',
        priceType                => 'AL',
        priceTypeQualifierID     => 'AL',
        rTitle                   => 'AF',
        rIsbn13                  => 'AK',
        rImprint                 => 'AC',
        countryCode              => 'T',
        rUnits                   => 'H',
        rListPrice               => 'I',
        rListPriceCurrency       => 'J',
        rNativeListPrice         => 'I',
        rNativeListPriceCurrency => 'J',
        rRevenue                 => 'O',
        currencyCode             => 'P',
        rComments                => 'AL',
    }
}

sub _unverifiedFieldMap {}
sub _headerIdentifier   { rIsbn13 => 'Alternate identifier' }

sub rServiceName  { 'De Marque' }
sub _useIsSaleRec { 1 }

sub purchaseType {
    my $self = shift;

    my $type = $self->_getByFieldName('rPurchaseType') || '';
    return BookPub::DB::Item::Sale::kPurchaseTypeDownload if $type =~ /^purchase$/i;
}

sub productType {
    my $self = shift;

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

    $self->fail("Unknown product type: '$type'");
}

sub formatType {
    my $self = shift;

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

    return BookPub::DB::Item::Sale::kFormatTypeAudioUnknown if $type =~ /^audio$/i;

    return $self->SUPER::formatType($type);
}

sub priceTypeQualifierID {
    my $self = shift;

    my $type = $self->_getByFieldName('priceTypeQualifierID') || '';
    return BookPub::DB::Item::PriceTypeQualifier::kCorporate if $type =~ /^library$/i;

    return undef;
}

sub priceType {
    my $self = shift;

    my $type = $self->_getByFieldName('priceType') || '';
    return 'rrp' if $type =~ /^library$/i;
    return 'agency' if $type =~ /^consumer$/i;
}

sub dateBegin {
    my $self = shift;

    my $date = $self->_getByFieldName('dateBegin') || '';
    my ($d, $m, $y);

    # YYYY-MM-DD
    if ( ($y, $m, $d) = $date =~ /^(\d{4}).(\d{1,2}).(\d{1,2})/) {
        return sprintf ("%04d-%02d-%02d", $y, $m, $d);
    }
}

sub dateEnd {
    my $self = shift;

    my $date = $self->_getByFieldName('dateEnd') || '';
    my ($d, $m, $y);

    # YYYY-MM-DD
    if ( ($y, $m, $d) = $date =~ /^(\d{4}).(\d{1,2}).(\d{1,2})/) {
        return sprintf ("%04d-%02d-%02d", $y, $m, $d);
    }
}

sub isFree {
    my $self = shift;

    return (((!$self->rRevenue || $self->rRevenue =~ /^0.0+/) && $self->rUnits) ? 'Y' : 'N');
}

1;
