package BookPub::Import::Importer::Gardners::Version5;

use strict;

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

sub _fieldMap {
    {
        # Detail
        priceType              => 'A1',
        currencyCode           => 'H',
        countryCode            => 'G',
        dateBegin              => 'P',
        rIsbn13                => 'A',
        rTitle                 => 'C',
        rUnits                 => 'E',
        rListPrice             => 'L',
        rListPriceCurrency     => 'H',
        rPurchasePrice         => 'I',
        rPurchasePriceCurrency => 'H',
        rRevenue               => 'M',
    };
}

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

sub purchaseType  { BookPub::DB::Item::Sale::kPurchaseTypeDownload }
sub productType   { BookPub::DB::Item::Sale::kProductTypeEBook }
sub _useIsSaleRec { 1 }
sub _dateFormat   { [ 'eur', 'iso' ] }

sub rTaxUnitPrice {
    my $self           = shift;
    my $rPurchasePrice = $self->_getByFieldName('rPurchasePrice');
    my $rListPrice     = $self->_getByFieldName('rListPrice');

    if ( $rPurchasePrice && $rListPrice ) {
        return $rPurchasePrice - $rListPrice;
    }
    return 0;
}

sub priceType {
    my $self   = shift;
    my $string = $self->_getByFieldName('priceType');

    if ( $string =~ /agency/i ) {
        return 'agency';
    }

    if ( $string =~ /rrp/i ) {
        return 'rrp';
    }
    $self->fail("Unable to find priceType in: $string");
}

sub _dateNormalization {
    my $self = shift;
    my $date = $self->_getByFieldName('dateBegin');
    if ( !$date ) {
        return 'month';
    }
}

sub _processLine {
    my $self = shift;
    my $isbn = $self->_getByFieldName('rIsbn13');

    if ( $isbn eq 'Total Qty Sold' ) {
        $self->{_endOfData} = 1;
    }

    return $self->SUPER::_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();
}

1;
