package BookPub::Import::Importer::Amazon::Version27;

use strict;

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

use Date::Calc qw( Add_Delta_YM );

sub _headerIdentifier { ( serviceProductID => 'ASIN' ) }

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

sub _useIsSaleRec { 1 }

sub rServiceName { 'Amazon' }
sub priceType    { 'rrp' }
sub purchaseType { BookPub::DB::Item::Sale::kPurchaseTypeDownload }
sub productType  { BookPub::DB::Item::Sale::kProductTypeEBook }

sub _dateNormalization { '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 _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();
}

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 {

        # here we want to treat UK as GB
        if ( $1 eq 'UK' ) {
            $obj = Common::Country->Get('GB');
            return $obj->alpha2;
        } else {
            $self->fail("Invalid country code: $1");
        }
    }
}

1;
