package BookPub::Import::Importer::EBook::Version21;

use strict;

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

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

sub _fieldMap {
    {
        dateBegin            => 'A',
        dateEnd              => 'A',
        rPurchaseType        => 'I',
        purchaseType         => 'I',
        rTitle               => 'E',
        rIsbn13              => 'H',
        rImprint             => 'D',
        countryCode          => 'AA',
        serviceProductID     => 'F',
        rUnits               => 'S',
        rListPriceCurrency   => 'L',
        rCOGS                => 'V',
        rRevenue             => 'W',
        currencyCode         => 'L',
        rPromoCode           => 'P',
        rModel               => 'J',
        rTransactionCategory => 'I',
        rComments            => 'Q',
    };
}

sub _unverifiedFieldMap {
    {
        salesPrice       => 'O',
        salePricePerUnit => 'R',
    };
}

sub _headerIdentifier { rTitle => 'Title' }

sub _useIsSaleRec { 1 }
sub priceType     { 'rrp' }
sub formatType    { BookPub::DB::Item::Sale::kFormatTypeEBL }
sub rFormat       { BookPub::DB::Item::Sale::kFormatTypeEBL }
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 purchaseType {
    my $self = shift;

    my $type = $self->_getByFieldName('purchaseType') || '';
    if ( $type =~ /^(?:Auto-Purchase|Firm Order|Upgrade|ATO Purchase)$/i ) {
        return BookPub::DB::Item::Sale::kPurchaseTypeDownload;
    } elsif ( $type =~ /^(?:STL|ATO Loan)$/i) {
        return BookPub::DB::Item::Sale::kPurchaseTypeLoan;
    }

    return $self->SUPER::purchaseType();
}

sub rUnits {
    my $self = shift;

    my $units = $self->_getByFieldName('rUnits') || 0;

    return $units if $units =~ /^[+-]?\d+$/;
    return 1 if $units < 1;
    return floor($units);
}

sub rListPrice {
    my $self = shift;

    my $salesPrice       = $self->_getByFieldName('salesPrice')       || 0;
    my $salePricePerUnit = $self->_getByFieldName('salePricePerUnit') || 0;
    my $rComments        = $self->_getByFieldName('rComments')        || 0;

    if ( $salesPrice ne $salePricePerUnit && $rComments !~ /^[+-]?0(?:.0+)?$/ ) {
        return $salePricePerUnit;
    }

    return $salesPrice;
}

sub _isSaleRec {
    my $self = shift;

    my $rIsbn13  = $self->_getByFieldName('rIsbn13');
    my $rTitle   = $self->_getByFieldName('rTitle');
    my $rRevenue = $self->_getByFieldName('rRevenue');
    my $rUnits   = $self->rUnits;

    return 0 unless $rIsbn13 && $rTitle && ($rUnits || $rRevenue);
    return $self->SUPER::_isSaleRec();
}


1;
