package BookPub::Import::Importer::Amazon::Version41;

use strict;

use Date::Calc qw( Add_Delta_YM );

use lib '/app/tools/common/lib';
use Common::Country;

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

sub _fieldMap {
    {
        rPurchaseType    => 'P',
        serviceProductID => 'C',
        currencyCode     => 'V',
        dateBegin        => 'B',
        dateEnd          => 'B',
        rFormat          => 'J',
        isbn             => 'F',
        rTitle           => 'G',
        rAuthor          => 'H',
        rImprint         => 'I',
        rUnits           => 'M',
        rAdjustments     => 'N',
        rListPrice       => 'O',
        rRevenue         => 'Y',
    };
}

sub _useIsSaleRec { 1 }

# the dates are the beginning and end of the previous month
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 _getDateEnd { shift->_getDateBegin() }

# deriving discount
sub rDiscount {
    my $self    = shift;
    my $list    = $self->_getByFieldName('rListPrice');
    my $revenue = $self->_getByFieldName('rRevenue');
    my $discount;

    if ( $list && $list != 0 ) {
        my $revenue = $self->rRevenue;
        my $units   = $self->rUnits;
        my $price;

        if ( $units == 0 ) {
            return 0;
        } else {
            $price = $revenue / $units;
        }

        $discount = 1 - ( $price / $list );
    }

    return $discount;
}

1;
