package BookPub::Import::Importer::Bokbasen:v1;

use strict;

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

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

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

sub _headerIdentifier { ( rIsbn13 => qr/Isbn/i ) }    # may (or may not) have byte order marker at beginning of file
sub _useIsSaleRec { 1 }

sub _dateNormalization { 'month' }
sub _dateFormat        { 'text' }
sub purchaseType       { BookPub::DB::Item::Sale::kPurchaseTypeDownload }
sub productType        { BookPub::DB::Item::Sale::kProductTypeEBook }
sub priceType          { 'agency+tax' }

sub _getDateBegin {
    my $self = shift;
    my $date = $self->filename;

    if ( $date =~ /_(\w{3})(\d\d).csv/i ) {
        return "$1-$2";
    } else {
        $self->fail("Unrecognized date in filename: '$date'");
    }
}

sub _getDateEnd { shift->_getDateBegin }

sub currencyCode {
    my $self = shift;
    my $code = $self->_getByFieldName('currencyCode');

    if ( $code =~ /Net Sales Proceeds (\w{3})$/i ) {
        $code = $1;
    }

    return $code;
}

sub discount {
    my $self = shift;

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

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

    return 0;
}

1;
