package BookPub::Import::Importer::Amazon::Version51;

use strict;

use lib '/app/tools/common/lib';
use Common::Country;
use Date::Calc qw( Add_Delta_YM );

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

sub _fieldMap {
    {
        serviceProductID         => 'B',
        currencyCode             => 'X',
        countryCode              => 'Y',
        dateBegin                => 'A',
        dateEnd                  => 'A',
        rFormat                  => 'I',
        isbn                     => 'E',
        rTitle                   => 'F',
        rAuthor                  => 'G',
        rImprint                 => 'H',
        rUnits                   => 'L',
        rSales                   => 'J',
        rReturns                 => 'K',
        rAdjustments             => 'N',
        rListPrice               => 'Q',
        rListPriceCurrency       => 'R',
        rNativeListPrice         => 'Q',
        rNativeListPriceCurrency => 'R',
        rPurchasePrice           => 'O',
        rPurchasePriceCurrency   => 'P',
        rDiscount                => 'S',
        rRevenue                 => 'W',
        rChannel                 => 'Z',
    };
}

# The module we inherit from (Version48) gets the country from the filename.  Here
# we want to read it from the sales entries
sub countryCode { shift->_getByFieldName('countryCode') }

sub rServiceName { 'Amazon' }

sub _getDateBegin {
    my $self = shift;

    my $date = $self->_getByFieldName('dateBegin') || "";

    if ($date =~ /(\d{1,2})\/(\d{1,2})\/(\d{4})/ ) {
        my ( $year, $month, $day ) = Add_Delta_YM( $3, $2, $1, 0, -1 );
        return sprintf( "%04d-%02d-%02d", $year, $month, $day );
    }
}

sub _getDateEnd {
    my $self = shift;

    my $date = $self->_getByFieldName('dateEnd') || "";

    if ( $date =~ /(\d{1,2})\/(\d{1,2})\/(\d{4})/ ) {
        my ( $year, $month, $day ) = Add_Delta_YM( $3, $2, $1, 0, -1 );
        return sprintf( "%04d-%02d-%02d", $year, $month, $day );
    }
}

sub isFree {
    my $self = shift;

    return ((!$self->rRevenue || $self->rRevenue eq '0.0') && $self->rUnits) ? 'Y' : 'N';
}

1;
