package BookPub::Import::Importer::Amazon::Version85;

use strict;

use lib '/app/tools/common/lib';
use lib '/app/tools/bookpub/lib';

use base 'BookPub::Import::Importer::Amazon::Version8';

use Date::Calc qw( Add_Delta_YM );
use Common::Country;

sub _headerIdentifier { ( rAuthor => qr/Author/ ) }

sub _fieldMap {
    {
        dateBegin              => 'A',
        rFormat                => 'I',
        rAuthor                => 'G',
        rTitle                 => 'F',
        rIsbn13                => 'E',
        rImprint               => 'H',
        countryCode            => 'X',
        serviceProductID       => 'B',
        rReturns               => 'K',
        rSales                 => 'J',
        rUnits                 => 'L',
        rAdjustments           => 'N',
        rListPrice             => 'S',
        rListPriceCurrency     => 'T',
        rPurchasePrice         => 'O',
        rPurchasePriceCurrency => 'P',
        rDiscount              => 'U',
        rRevenue               => 'V',
        currencyCode           => 'W',
    }
}

sub _useIsSaleRec              { 1 }
sub _autoParseTitleAndSubtitle { 1 }
sub purchaseType               { BookPub::DB::Item::Sale::kPurchaseTypeDownload }
sub rPurchaseType              { BookPub::DB::Item::Sale::kPurchaseTypeDownload }
sub productType                { BookPub::DB::Item::Sale::kProductTypeEBook }
sub rProductType               { BookPub::DB::Item::Sale::kProductTypeEBook }

sub rServiceName {
    return BookPub::Tracker::Service::GetDefaultServiceName( service_id => shift->serviceID );
}

sub priceType {
    my $self    = shift;

    my $country = $self->countryCode();
    my $client = Common::RSApp::GetClientID();

    return 'agency' if ( $client == 355 || ($client == 318 && ($country =~ /^(?:US|CA)$/)) ); # Macmillan CA/US or HUK
    return 'rrp'    if ( $client =~ /^(?:314|328|361)$/ || ($client == 318 && ($country !~ /^(?:US|CA)$/)) ); # Bloomsbury ALL or Macmillan ROW
}

sub _processLine {
    my $self = shift;
    my $date = $self->_getByFieldName('dateBegin');

    if ( $date && $date =~ /Invoice Date/ ) {
        $self->{_endOfData} = 1;
    }

    return $self->SUPER::_processLine(@_);
}

sub isFree {
    my $self = shift;

    my $revenue = $self->_getByFieldName("rRevenue") || 0;
    my $units   = $self->_getByFieldName("rUnits")   || 0;

    $revenue =~ s/^0\.0+$/0/g;

    return !$revenue && $units ? 'Y' : 'N';
}

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;
