package BookPub::Import::Importer::Amazon::Version16;

use strict;

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

use Date::Calc qw( Add_Delta_YM );

sub _headerIdentifier { ( dateBegin => qr/Invoice Date/ ) }

sub _fieldMap {
    my $self = shift;

    my %fieldMap = (
        16 => {
            serviceProductID   => 'B',
            currencyCode       => 'U',
            countryCode        => 'V',
            dateBegin          => 'A',
            rFormat            => 'I',
            isbn               => 'E',
            rTitle             => 'F',
            rAuthor            => 'G',
            rImprint           => 'H',
            rUnits             => 'L',
            rSales             => 'J',
            rReturns           => 'K',
            rAdjustments       => 'N',
            rPurchasePrice     => 'O',
            rListPrice         => 'Q',
            rListPriceCurrency => 'R',
            rDiscount          => 'S',
            rRevenue           => 'T',
        },
        39 => {
            serviceProductID   => 'B',
            currencyCode       => 'U',
            countryCode        => 'V',
            dateBegin          => 'A',
            rFormat            => 'I',
            isbn               => 'E',
            rTitle             => 'F',
            rAuthor            => 'G',
            rImprint           => 'H',
            rUnits             => 'L',
            rSales             => 'J',
            rReturns           => 'K',
            rAdjustments       => 'N',
            rPurchasePrice     => 'O',
            rPurchasePriceCurrency => 'P',
            rListPrice         => 'Q',
            rListPriceCurrency => 'R',
            rDiscount          => 'S',
            rRevenue           => 'T',
            rPurchaseType      => 'W',
        },
    );

    return $fieldMap{ $self->_version() };
}

sub _useIsSaleRec { 1 }
sub productType   { BookPub::DB::Item::Sale::kProductTypeEBook }

sub _autoParseTitleAndSubtitle { 1 }

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

sub priceType {
    my $self = shift;

    if ( Common::RSApp::GetClientID() == 359 && $self->_version == 39 ) {    # MMUK
        return 'agency' ;
    }

    return 'rrp';
}

sub purchaseType {
    my $self = shift;
    my $type = $self->rPurchaseType();

    if ( lc($type) eq 'lending' ) {
        return BookPub::DB::Item::Sale::kPurchaseTypeLoan;
    }

    return BookPub::DB::Item::Sale::kPurchaseTypeDownload;
}

sub _processLine {
    my $self = shift;
    my $id   = $self->serviceProductID();

    if ( $id && $id =~ m/Invoice[_ ]Number/i ) {
        $self->{_endOfData} = 1;
    }

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

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

    if ( $date && $date =~ /(\d{1,2})\/(\d{1,2})\/(\d{4})/ ) {

        # We've got some dates at the bottom of the file that we want to ignore anyway,
        # but this function is called before _isValidSaleRecord, so we need to do something
        # here to skip them.

        # Euro date...
        my ( $year, $month, $day ) = Add_Delta_YM( $3, $2, $1, 0, -1 );

        return sprintf( "%04d-%02d-%02d", $year, $month, $day );
    }
}

sub _dateNormalization { 'month' }

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();
}

sub rRevenue {
    my $self    = shift;
    my $revenue = $self->SUPER::rRevenue();

    if ( $revenue =~ s/[\(\)]//g ) {
        $revenue *= -1;
    }

    return $revenue;
}

sub rSales {
    my $self    = shift;
    my $sales   = $self->_getByFieldName('rSales');
    my $returns = $self->_getByFieldName('rReturns');
    my $units   = $sales - $returns;
    my $revenue = $self->revenue();

    if ( ( $units > 0 && $revenue < 0 ) || ( $units < 0 && $revenue > 0 ) ) {
        return $returns;
    }

    return $sales;
}

sub rReturns {
    my $self    = shift;
    my $sales   = $self->_getByFieldName('rSales');
    my $returns = $self->_getByFieldName('rReturns');
    my $units   = $sales - $returns;
    my $revenue = $self->revenue();

    if ( ( $units > 0 && $revenue < 0 ) || ( $units < 0 && $revenue > 0 ) ) {
        return $sales;
    }

    return $returns;
}

1;
