package BookPub::Import::Importer::DawsonBooks::Version1;

use strict;

use Data::Dumper;

use lib '/app/tools/common/lib';
use Common::Date;
use Common::Log;

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

sub _fieldMap {
    {
        # Header
        currencyCode => 'B2',

        # Data
        dateBegin            => 'C',
        dateEnd              => 'C',
        rTitle               => 'L',
        rIsbn13              => 'J',
        rAuthor              => 'M',
        rUnits               => 'F',
        rListPrice           => 'O',
        rListPriceCurrency   => 'Q',
        rDiscount            => 'S',
        rRevenue             => 'R',
        purchaseType         => 'N',
        rDuration            => 'N',
        rTransactionCategory => 'N',
    };
}

sub _unverifiedFieldMap {
    {

        costPrice => 'P',
    };
}

sub _headerIdentifier { ( rTitle => 'Title' ) }

sub productType                { BookPub::DB::Item::Sale::kProductTypeEBook }
sub _dateFormat                { [ 'us', 'iso' ] }
sub priceType                  { 'rrp' }
sub countryCode                { 'UK' }
sub _autoParseTitleAndSubtitle { 1 }
sub _useIsSaleRec              { 1 }

sub _processLine {
    my $self = shift;
    my $cp   = $self->_getByFieldName('costPrice');

    if ( $cp && $cp =~ m/NET/i ) {
        $self->{_endOfData} = 1;
    }

    return $self->BookPub::Import::Importer::_processLine(@_);
}

sub _isSaleRec {
    my $self = shift;

    # If we've set the end of data flag in processLine, we are done.
    return if ( $self->{_endOfData} );

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

# if negative revenue, return a negative unit, otherwise a positive one
sub units {
    my $self = shift;
    my $rev  = $self->_getByFieldName('rRevenue');
    my $qty  = $self->_getByFieldName('rUnits');

    return $rev < 0 ? -1 * $qty : $qty;
}

# the sales file had a non-ascii character as the first character of an otherwise
# valid ISBN13 value.  This caused the ISBN to be blank, but not NULL on import.
# Fixing by trimming any non-digit characters from the value
sub rIsbn13 {
    my $self = shift;
    my $value = $self->_getByFieldName('rIsbn13') || return;
    my $isbn;

    if ( $value =~ m/(\d{13})/ ) {
        $isbn = $1;
    }
    return $isbn;
}

sub rDiscount {
    my $self = shift;
    my $discount = $self->_getByFieldName('rDiscount') || return;

    $discount = abs($discount);

    return $discount;
}

sub purchaseType {
    my $self  = shift;
    my $value = $self->_getByFieldName('purchaseType');

    if ( $value == 0 ) { return BookPub::DB::Item::Sale::kPurchaseTypeDownload; }
    if ( $value =~ /^(\d+)$/ && $value > 0 ) { return BookPub::DB::Item::Sale::kPurchaseTypeLoan; }

    $self->fail( "Unknown purchaseType value: " . $value );
}

1;
