package BookPub::Import::Importer::Amazon::Version72;

use strict;
use warnings;

use lib '/app/tools/common/lib';

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

use Date::Calc qw/Add_Delta_YM/;


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

sub _unverifiedFieldMap {{}}

sub _headerIdentifier { rIsbn13 => 'Digital ISBN' }

sub _useIsSaleRec              { 1 }
sub _autoParseTitleAndSubtitle { 1 }
sub priceType                  { 'agency+tax' }
sub purchaseType               { BookPub::DB::Item::Sale::kPurchaseTypeSubscriptionDL  }
sub rServiceName               { 'Amazon' }
sub countryCode                {
    my $self = shift;

    my $filename = $self->filename() || "";
    $filename =~ /_(\w{2})\./;

    return $1 if $1;

    $self->fail("Unable to determine countryCode from filename: '$filename'");
}

sub _getDateBegin {
    my $self = shift;

    my $date = $self->_getByFieldName('dateBegin') || ''; #d/m/YY
    if ( $date =~ /(\d{1,2})\/(\d{1,2})\/(\d{2})/ ) {
        my ($y, $m, $d) = ($3, $2, $1);
        $y = "20$y" if (length($y) < 4);
        ($y, $m, $d) = Add_Delta_YM($y, $m, $d, 0, -1);

        return sprintf( "%04d-%02d-%02d", $y, $m, $d );
    }

    $self->fail("Unable to determine dateBegin from: '$date'");
}

sub _getDateEnd { shift->_getDateBegin() }

sub productType {
    my $self = shift;

    my $type = $self->_getByFieldName('rProductType') || '';
    if ( $type =~ /^Kindle eBook$/i ) {
        return BookPub::DB::Item::Sale::kProductTypeEBook;
    }

    $self->fail("Unable to determine product_type from: '$type'");
}

sub _isSaleRec {
    my $self = shift;

    my $isbn = $self->_getByFieldName('rIsbn13') || '';
    return unless $isbn;

    return $self->SUPER::_isSaleRec();
}

1;
