package BookPub::Import::Importer::Amazon::Version18;

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 { ( dateBegin => qr/Invoice[ _]Date/i ) }

sub _fieldMap {
    {
        dateBegin          => 'B',
        rPurchaseType      => 'P',
        rFormat            => 'J',
        rAuthor            => 'H',
        rTitle             => 'G',
        rIsbn13            => 'F',
        rImprint           => 'I',
        serviceProductID   => 'C',
        rReturns           => 'L',
        rSales             => 'K',
        rUnits             => 'M',
        rAdjustments       => 'N',
        rListPrice         => 'O',
        rListPriceCurrency => 'V',
        rDiscount          => 'T',
        rRevenue           => 'U',
        currencyCode       => 'V',
        rDuration          => 'R',
        rPreviousDuration  => 'Q',
    };
}

sub _useIsSaleRec              { 1 }
sub _autoParseTitleAndSubtitle { 1 }
sub priceType                  { 'rrp' }
sub productType                { BookPub::DB::Item::Sale::kProductTypeEBook }
sub rProductType               { BookPub::DB::Item::Sale::kProductTypeEBook }

sub rServiceName {
    return BookPub::Tracker::Service::GetDefaultServiceName(
        service_id => shift->serviceID
    );
}

sub units {

    # We need to make sure that the sign of the units matches the sign of the revenue
    my $self    = shift;
    my $units   = $self->_getByFieldName('rUnits');
    my $revenue = $self->rRevenue;

    if ( ( $revenue < 0 && $units > 0 ) || ( $revenue > 0 && $units < 0 ) ) {
        $units *= -1;
    }

    return $units;
}

sub formatType {
    my $self       = shift;
    my $formatType = $self->_getByFieldName('rFormat');

    if ( lc($formatType) eq 'kindle ebook' ) {
        return BookPub::DB::Item::Sale::kFormatTypeKindle;
    } elsif ($formatType) {
        $self->fail("Unknown format type '$formatType'");
    }
}

sub purchaseType {
    my $self         = shift;
    my $purchaseType = $self->_getByFieldName('rPurchaseType');

    if ( lc($purchaseType) eq 'checkout' ) {
        return BookPub::DB::Item::Sale::kPurchaseTypeLoan;
    } elsif ( lc($purchaseType) eq 'extension' ) {
        return BookPub::DB::Item::Sale::kPurchaseTypeLoan;
    } elsif ( lc($purchaseType) eq 'purchase' ) {
        return BookPub::DB::Item::Sale::kPurchaseTypeDownload;
    } elsif ($purchaseType) {
        $self->fail("Unknown purchase type '$purchaseType'");
    }
}

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;

    $date = "0".$date if ($date !~ /^[10]/);

    if ( $date && $date =~ /(\d{1,2})[\/\.\-]?(\d{1,2})[\/\.\-]?(\d{4})/ ) {

        # We've got some dates at the bottom of the file that we want to ignore anyway,
        # but this function is called before _isValidSaleRecord, so we need to do something
        # here to skip them.

        my ( $year, $month, $day ) = Add_Delta_YM( $3, $1, $2, 0, -1 );

        return sprintf( "%04d-%02d-%02d", $year, $month, $day );
    }
}

sub _dateNormalization { 'month' }

sub rRevenue {
    my $self    = shift;
    my $revenue = $self->SUPER::rRevenue();

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

    return $revenue;
}

sub isFree {
    my $self = shift;

    my $revenue = $self->_getByFieldName("rRevenue") || 0;
    my $units = $self->_getByFieldName("rUnits") || 0;

    $revenue =~ s/^0\.0+$/0/g;

    return !$revenue && $units ? 'Y' : 'N';
}

1;
