package BookPub::Import::Importer::Amazon::Version9;

use strict;

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

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

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

sub _fieldMap {
    {
        serviceProductID   => 'B',
        currencyCode       => 'H',
        dateBegin          => 'A',
        rTitle             => 'C',
        rUnits             => 'F',
        rSales             => 'D',
        rReturns           => 'E',
        rListPrice         => 'G',
        rListPriceCurrency => 'H',
        rDiscount          => 'I',
        rRevenue           => 'J',
    };
}

sub priceType    { 'rrp' }
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 period {
    my $self = shift;

    return $self->{_period} if ( $self->{_period} );

    $self->fail( "Unable to determine date from filename: " . $self->filename )
      unless ( $self->filename =~ /(\d{8}).(\d{8})/ );

    my $date = new Common::Date( date => $1, type => 'numerical_year_first' );

    $self->{_period} = $date->monthBegin();

    return $self->{_period};
}

sub _getDateBegin {
    my $self = shift;

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

    if ( $date =~ /^[\d\-\/]+$/ ) {
        $self->{_dateBegin} = $date;
    }

    return $self->{_dateBegin};
}

sub dateBegin {
    my $self = shift;
    my $date = $self->SUPER::dateBegin() || return;

    # Only capture sales that are reported in the period specified in the filename
    return unless ( $date eq $self->period() );

    return $date;
}

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 _isValidSaleRecord {
    my $self = shift;

    return ( $self->rTitle || $self->rAuthor || $self->rIsbn13 ) && $self->dateBegin;
}

1;
