package BookPub::Import::Importer::Amazon::Version15;

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/ ) }

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

sub _useIsSaleRec { 1 }

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

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 {
        $self->fail("Invalid country code: $cc");
    }
}

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

    # DD/MM/YYYY or MM/DD/YYYY
    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 );

        # Let's try to detect 'euro' style dates.
        if ( $1 == 1 ) {
            ( $year, $month, $day ) = Add_Delta_YM( $3, $2, $1, 0, -1 );
        } else {
            ( $year, $month, $day ) = Add_Delta_YM( $3, $1, $2, 0, -1 );
        }

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

    # YYYY-MM-DD or YYYY/MM/DD
    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 _dateNormalization { 'month' }

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

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

    return $revenue;
}

sub rListPriceCurrency {
    my $self              = shift;
    my $listPriceCurrency = $self->_getByFieldName('rListPriceCurrency');
    my $revenueCurrency   = $self->_getByFieldName('currencyCode');

    # For Macmillan and RLPG, we're going to set the list price currency to the revenue currency.
    # We'll also be converting the list price with the conversion rate.
    # If it's already in USD, we can just leave it alone.
    if (   ( Common::RSApp::GetClientID == 318 || Common::RSApp::GetClientID == 346 )
        && $listPriceCurrency ne 'USD'
        && $listPriceCurrency ne $revenueCurrency ) {
        $listPriceCurrency = $revenueCurrency;
    }

    return $listPriceCurrency;
}

sub rListPrice {
    my $self              = shift;
    my $listPrice         = $self->_getByFieldName('rListPrice');
    my $listPriceCurrency = $self->_getByFieldName('rListPriceCurrency');
    my $revenueCurrency   = $self->_getByFieldName('currencyCode');

    # For Macmillan and RLPG, we're going to convert the list price if it's not in USD
    # AND it's in a different currency than the revenue is.
    #
    if (   ( Common::RSApp::GetClientID == 318 || Common::RSApp::GetClientID == 346 )
        && $listPriceCurrency ne 'USD'
        && $listPriceCurrency ne $revenueCurrency ) {
        $listPrice =~ s/,//g;
        my $revenue  = $self->rRevenue;
        my $units    = $self->units();
        my $discount = $self->rDiscount;
        if ( $discount > 1 ) {
            $discount /= 100;
        }
        if ($units) {
            my $conversionRate = $revenue / ( $listPrice * $units * ( ( 1 - $discount ) / 1 ) );
            $listPrice *= $conversionRate;
        }
    }

    return abs($listPrice);
}

1;
