package BookPub::Import::Importer::Perusall::Version3;

use strict;

use lib '/app/tools/bookpub/lib';

use base 'BookPub::Import::Importer';

sub _fieldMap {
    {
        dateBegin      => 'B',
        rPurchaseType  => 'L',
        rAuthor        => 'J',
        rTitle         => 'I',
        rIsbn13        => 'H',
        rInstitution   => 'D',
        rState         => 'F',
        countryCode    => 'G',
        rListPrice     => 'P',
        rTaxAmount     => 'O',
        rPurchasePrice => 'N',
        rCOGS          => 'W',
        rRevenue       => 'V',
        currencyCode   => 'P',
        rDuration      => 'M',
        rComments      => 'X',
    };
}

sub _unverifiedFieldMap {
    { notes => 'C', };
}

sub _headerIdentifier { ( rIsbn13 => 'ISBN' ) }

sub _processHeader {
    my $self = shift;

    unless ($self->{_currency}) {
        my $currency = $self->_getByFieldName("currencyCode");
        $currency =~ /\((\w{3})\)$/;
        $self->{_currency} = $1 if $1;
    }
    return $self->SUPER::_processHeader();
}

sub _useIsSaleRec          { 1 }
sub productType            { BookPub::DB::Item::Sale::kProductTypeEBook }
sub rProductType           { BookPub::DB::Item::Sale::kProductTypeEBook }
sub currencyCode           { $_[0]->{_currency} if $_[0]->{_currency} }
sub rListPriceCurrency     { shift->currencyCode }
sub rPurchasePriceCurrency { shift->currencyCode }
sub priceType              { Common::RSApp::GetClientID == 318 ? 'agency' : 'rrp' }    # MMUS

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

sub _isSaleRec {
    my $self = shift;

    return $self->rRevenue() && $self->_getByFieldName('notes') !~ /refunded/i;
}

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

    return $1 if ( $date =~ /^(\d{4}-\d{2}-\d{2}).+$/ );

    $self->fail("Cannot determine date from '$date'");
}

sub purchaseType {
    my $self = shift;

    my $purchaseType;
    if ( $self->rPurchaseType =~ /^Perpetual$/i ) {
        $purchaseType = BookPub::DB::Item::Sale::kPurchaseTypeSubscriptionDL;
    }
    else {
        $purchaseType = BookPub::DB::Item::Sale::kPurchaseTypeLoan;
    }

    return $purchaseType;
}

sub rUnits {
    my $self = shift;

    return $self->revenue < 0 ? -1 : 1;
}

sub rRevenue {
    my $self = shift;

    my $revenue = $self->_getByFieldName('rRevenue');
    $revenue =~ s/\$//;

    return $revenue;
}

sub rTaxAmount {
    my $self = shift;

    my $tax = $self->_getByFieldName('rTaxAmount');
    $tax =~ s/\$//;

    return $tax;
}

sub rListPrice {
    my $self = shift;

    my $listPrice = $self->_getByFieldName('rListPrice');
    $listPrice =~ s/\$//;

    return abs($listPrice);
}

sub rPurchasePrice {
    my $self          = shift;
    my $purchasePrice = $self->_getByFieldName('rPurchasePrice');
    $purchasePrice =~ s/\$//;

    return abs($purchasePrice);
}

1;

