package BookPub::Import::Importer::Amazon::Version24;

use strict;
use warnings;

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 => 'Date de facturation (Invoice Date)' ) }

sub _fieldMap {
    my $self = shift;

    my %map = (
        24 => {
            serviceProductID       => 'B',
            currencyCode           => 'U',
            dateBegin              => 'A',
            rFormat                => 'I',
            rIsbn13                => 'E',
            rTitle                 => 'F',
            rAuthor                => 'G',
            rImprint               => 'H',
            rUnits                 => 'L',
            rSales                 => 'J',
            rReturns               => 'K',
            rAdjustments           => 'N',
            rListPrice             => 'Q',
            rListPriceCurrency     => 'R',
            rPurchasePrice         => 'O',
            rDiscount              => 'S',
            rRevenue               => 'T',
            rPurchasePriceCurrency => 'P',
        },
        68 => {
            dateBegin              => 'A',
            rFormat                => 'I',
            rAuthor                => 'G',
            rTitle                 => 'F',
            rIsbn13                => 'E',
            rImprint               => 'H',
            serviceProductID       => 'B',
            rReturns               => 'K',
            rSales                 => 'J',
            rUnits                 => 'L',
            rAdjustments           => 'N',
            rListPrice             => 'Q',
            rListPriceCurrency     => 'R',
            rPurchasePrice         => 'O',
            rPurchasePriceCurrency => 'P',
            rDiscount              => 'S',
            rRevenue               => 'T',
            currencyCode           => 'U',
            rModel                 => 'V',
        }
    );

    return $map{ $self->version };
}

sub _useIsSaleRec              { 1 }
sub _autoParseTitleAndSubtitle { 1 }

sub countryCode  { 'CA' }
sub purchaseType { BookPub::DB::Item::Sale::kPurchaseTypeDownload }
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 priceType {
    my $self = shift;
    my $type;

    if ( Common::RSApp::GetClientID == 335 ) {         # Berrett Koehler
        $type = 'rrp';
    } elsif ( Common::RSApp::GetClientID == 346 ) {    # Rowman Littlefield
        $type = 'rrp';
    } elsif ( Common::RSApp::GetClientID == 324 ) {    # Wiley
        $type = 'rrp';
    } else {
        $type = 'agency';
    }

    return $type;
}

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

    if ( $date && $date =~ /(\d{4})-(\d{2})-(\d{2})/ ) {
        my ( $year, $month, $day ) = Add_Delta_YM( $1, $2, $3, 0, -1 );

        return sprintf( "%04d-%02d-%02d", $year, $month, $day );
    } elsif ( $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 );
    }

}

sub _dateNormalization { 'month' }

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

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

    return $price;
}

sub rSales {
    my $self    = shift;
    my $sales   = $self->_getByFieldName('rSales');
    my $returns = $self->_getByFieldName('rReturns');
    my $units   = $sales - $returns;
    my $revenue = $self->revenue();

    if ( ( $units > 0 && $revenue < 0 ) || ( $units < 0 && $revenue > 0 ) ) {
        return $returns;
    }

    return $sales;
}

sub rReturns {
    my $self    = shift;
    my $sales   = $self->_getByFieldName('rSales');
    my $returns = $self->_getByFieldName('rReturns');
    my $units   = $sales - $returns;
    my $revenue = $self->revenue();

    if ( ( $units > 0 && $revenue < 0 ) || ( $units < 0 && $revenue > 0 ) ) {
        return $sales;
    }

    return $returns;
}

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;
    }
    # For Wiley
    elsif ( Common::RSApp::GetClientID == 324 && $listPriceCurrency ne 'CAD' ) {
        return $self->_getByFieldName('rPurchasePriceCurrency');
    }

    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;
        }
    }
    # For Wiley
    elsif ( Common::RSApp::GetClientID == 324 && $listPriceCurrency ne 'CAD' ) {
        $listPrice = $self->_getByFieldName('rPurchasePrice');
    }

    return abs($listPrice);
}

sub rDiscount {
    my $self     = shift;
    my $discount = $self->_getByFieldName('rDiscount');
    $discount /= 100;
    return $discount;
}

sub _processLine {
    my $self = shift;
    my $id   = $self->serviceProductID();

    if ( $id && $id =~ m/Invoice[_ ]Number/i ) {
        $self->{_endOfData} = 1;
    }

    return $self->SUPER::_processLine(@_);
}

sub rFormat {
    my $self = shift;

    my $rFormat = $self->_getByFieldName('rFormat');
    $rFormat =~ s/Kindl eBook/Kindle eBook/ig;

    return $rFormat;
}

sub isFree {
    my $self = shift;

    return !($self->rRevenue + 0) && ($self->rUnits + 0) ? 'Y' : 'N';
}

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;
