package BookPub::Import::Importer::Bokbasen::v2;

use strict;

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

sub _fieldMap {
    {
        rProductType       => 'K',
        rIsbn13            => 'A',
        countryCode        => 'H',
        rUnits             => 'B',
        rListPrice         => 'C',
        rListPriceCurrency => 'G',
        rRevenue           => 'J',
        rChannel           => 'D',
    };
}

sub _unverifiedFieldMap {
    {
        grossSales => 'E',
        netSales   => 'F',
    };
}

sub _headerIdentifier { ( rIsbn13 => qr/Isbn/i ) }
sub _useIsSaleRec { 1 }

sub rServiceName  { 'Bokbasen' }
sub purchaseType  { BookPub::DB::Item::Sale::kPurchaseTypeDownload }
sub rPurchaseType { shift->purchaseType }
sub priceType     { 'agency+tax' }
sub currencyCode  { 'EUR' }

sub productType {
    my $self = shift;

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

    return BookPub::DB::Item::Sale::kProductTypeEBook if ($type =~ /^(?:e-bok|ed|ebook)$/i);
    return BookPub::DB::Item::Sale::kProductTypeAudioBook if ($type =~ /^(?:lydfil|aj|audio)$/i);

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

sub _getDateBegin {
    my $self = shift;

    my $date = $self->filename;

    if ( $date =~ /^\w+[ _]+(\d{4})(\d{2})[ _]/i ) {
        return sprintf( '%04d-%02d-01', $1, $2 );
    } else {
        $self->fail("Unrecognized date in filename: '$date'");
    }
}

sub discount {
    my $self = shift;

    my $gross = $self->_getByFieldName('grossSales');
    my $net   = $self->_getByFieldName('netSales');

    if ($gross) {
        return 1 - ( $net / $gross );
    }

    return 0;
}

sub isFree {
    my $self = shift;

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

1;
