package BookPub::Import::Importer::Amazon::Version40;

use strict;

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

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

use Date::Calc qw( Add_Delta_YM );

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

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

    if ( $filename =~ /(\d{8})-(\d{4})(\d{2})(\d{2})/ ) {
        $filenameMonth = $3;
    } else {
        $self->fail("Can't determine date from filename: $filename");
    }

    # Sometimes the date is MM/DD/YYYY, sometimes DD/MM/YYYY
    # so we'll look at the date in the header and follow that
    # convention

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

        # if the sales month doesn't match the filename month, then we
        # use the filename month
        if ( $month != $filenameMonth && $day == $filenameMonth ) {
            $month = $filenameMonth;
        }

        # And we want to use the month before the sale date as the date
        ( $year, $month, $day ) = Add_Delta_YM( $year, $month, $day, 0, -1 );

        return sprintf( "%04d-%02d-%02d", $year, $month, $day );
    } else {
        $self->fail("Unexpected date format: $date");
    }
}

sub _getDateEnd {
    my $self = shift;
    return $self->_getDateBegin();
}

1;
