package BookPub::Import::Importer::Amazon::Version6;

use strict;

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

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

use Date::Calc qw( Add_Delta_YM );

sub _headerIdentifier { ( rTitle => 'Title' ) }

sub _fieldMap {
    {
        dateBegin          => 'A',
        serviceProductID   => 'B',
        currencyCode       => 'U',
        rFormat            => 'I',
        isbn               => 'E',
        rTitle             => 'F',
        rAuthor            => 'G',
        rImprint           => 'H',
        rUnits             => 'L',
        rSales             => 'J',
        rReturns           => 'K',
        rPurchasePrice     => 'O',
        rListPrice         => 'Q',
        rListPriceCurrency => 'R',
        rDiscount          => 'S',
        rRevenue           => 'T',
    };
}

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

sub countryCode {
    my $self = shift;

    my $filename = $self->filename();

    $self->fail("Country code missing from filename")
      unless ( $filename =~ /(?:_(\w{2})_|_(\w{2})\.)/ );

    my $cc = $1 || $2;
    my $obj = Common::Country->Get($cc);

    if ($obj) {
        return $obj->alpha2;
    } else {
        $self->fail("Invalid country code: $cc");
    }
}

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

    if ( $date && $date =~ /(\d{1,2})\/(\d{1,2})\/(\d{4})/ ) {
        my ( $year, $month, $day ) = Add_Delta_YM( $3, $1, $2, 0, -1 );
        return sprintf( "%04d-%02d-%02d", $year, $month, $day );
    } elsif ( $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 _dateNormalization { 'month' }

sub rRevenue {
    my $self = shift;
    my $price = $self->_getByFieldName('rRevenue') || return;

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

    return $price;
}

sub rListPrice {
    my $self = shift;
    my $price = $self->_getByFieldName('rListPrice') || return;

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

    return $price;
}

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;
