package BookPub::Import::Importer::Amazon::Version21;

use strict;

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

use Date::Calc qw( Add_Delta_YM );

sub _headerIdentifier { ( serviceProductID => 'ASIN' ) }

sub _fieldMap {
    {
        serviceProductID   => 'B',
        currencyCode       => 'V',
        countryCode        => 'W',
        dateBegin          => 'A',
        rFormat            => 'J',
        isbn               => 'E',
        rTitle             => 'G',
        rAuthor            => 'H',
        rImprint           => 'I',
        rUnits             => 'M',
        rSales             => 'K',
        rReturns           => 'L',
        rListPrice         => 'P',
        rListPriceCurrency => 'Q',
        rDiscount          => 'T',
        rRevenue           => 'U',
    };
}

sub _useIsSaleRec              { 1 }
sub _autoParseTitleAndSubtitle { 1 }
sub rServiceName               { 'Amazon' }
sub priceType                  { 'rrp' }
sub purchaseType               { BookPub::DB::Item::Sale::kPurchaseTypeDownload }
sub productType                { BookPub::DB::Item::Sale::kProductTypeEBook }

sub _dateNormalization { 'month' }

sub rRevenue {
    my $self    = shift;
    my $revenue = $self->_getByFieldName('rRevenue');

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

    return $revenue;
}

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

    if ( $date && $date =~ /(\d{4})[\/-](\d{1,2})[\/-](\d{1,2})/ ) {
        my ( $year, $month, $day ) = Add_Delta_YM( $1, $2, $3, 0, -1 );

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

sub rPurchasePrice {
    my $self = shift;
    my $purchasePrice;

    # Right now, we only know the formula to calculate this for Macmillan.
    if ( Common::RSApp::GetClientID == 318 ) {    # Macmillan
        my $revenue = $self->_getByFieldName('rRevenue');
        my $units   = $self->_getByFieldName('rUnits');
        if ($units) {
            $purchasePrice = ( $revenue / $units ) / 0.5;
        }
    }

    return $purchasePrice;
}

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

    if ( $id && $id =~ m/Invoice[_ ]Number/i ) {
        $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;
