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

use strict;

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

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

sub _fieldMap {
    {
        dateBegin     => 'A',
        rPurchaseType => 'F',
        rAuthor       => 'C',
        rTitle        => 'B',
        rIsbn13       => 'E',
        rInstitution  => 'J',
        rState        => 'K',
        countryCode   => 'L',
        rListPrice    => 'G',
        rRevenue      => 'I',
        rTaxUnitPrice => 'H',
    };
}

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

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

sub _useIsSaleRec { 1 }

sub productType        { BookPub::DB::Item::Sale::kProductTypeEBook }
sub priceType          { 'rrp' }
sub currencyCode       { 'USD' }
sub rListPriceCurrency { shift->currencyCode }

sub _isSaleRec {
    my $self = shift;

    return $self->rIsbn13 =~ /^\d{13}$/
      && $self->_getByFieldName('notes') ne 'refunded';
}

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

    if ( $date && $date =~ /(\w{3}) (\d{1,2}) / ) {

        my $day = $2;

        my $filename = $self->filename;

        if ( $filename =~ /(\d{4})[\s_](\d{2})\.csv/ ) {

            my $year  = $1;
            my $month = $2;

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

    }

    return $date;
}

sub purchaseType {
    my $self = shift;

    my $purchaseType;
    if ( $self->rPurchaseType eq 'Perpetual online access to text' ) {
        $purchaseType = BookPub::DB::Item::Sale::kPurchaseTypeSubscriptionDL;
    }

    return $purchaseType;
}

sub state {
    my $self = shift;

    my ($state) = $self->rState =~ /.*, ([A-Z][A-Z])$/;

    return $state;
}

sub rUnits {
    my $self = shift;

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

sub rTaxUnitPrice {
    my $self = shift;

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

    return $tax;
}

sub rRevenue {
    my $self = shift;

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

    return $revenue;
}

sub rListPrice {
    my $self = shift;

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

    return abs($listPrice);
}

1;

