package BookPub::Import::Importer::Follett_Higher_Education::Version2;

use strict;

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

sub _headerIdentifier { ( rTitle => 'Title' ) }

sub _fieldMap {
    {
        purchaseType => 'M',
        rPostalCode  => 'Q',
        dateBegin    => 'D',
        rIsbn10      => 'G',
        rIsbn13      => 'F',
        rTitle       => 'L',
        rAuthor      => 'K',
        rListPrice   => 'N',
        rRevenue     => 'O',
    };
}

sub purchaseType { BookPub::DB::Item::Sale::kPurchaseTypeDownload }
sub productType  { BookPub::DB::Item::Sale::kProductTypeEBook }
sub priceType    { 'rrp' }
sub currencyCode { 'USD' }
sub countryCode  { 'US' }

sub rUnits {
    my $self = shift;
    my $type = $self->_getByFieldName('purchaseType');

    if ( $type eq 'Sale' || $type eq 'Sale Correction' || $type eq 'Standard' ) {
        return 1;
    } elsif ( $type eq 'Refund' || $type eq 'Refund Correction' || $type eq 'Sale Reversal' ) {
        return -1;
    } else {
        $self->fail("Unknown purchaseType found: $type");
    }
}

sub rSales {
    my $self = shift;
    my $type = $self->_getByFieldName('purchaseType');

    if ( $type eq 'Sale' || $type eq 'Sale Correction' || $type eq 'Standard' ) {
        return 1;
    }
    return;
}

sub rReturns {
    my $self = shift;
    my $type = $self->_getByFieldName('purchaseType');

    if ( $type eq 'Refund' || $type eq 'Refund Correction' || $type eq 'Sale Reversal' ) {
        return 1;
    }
    return;
}

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

    if ( $price < 0 ) {
        $price *= -1;
    }

    return $price;
}

sub rTitle {
    my $self  = shift;
    my $title = $self->_getByFieldName('rTitle');

    if ( $title =~ /^(.+) \(ebook\) \d+\w{2}$/ ) {
        $title = $1;
    }

    return $title;
}

sub postalCode {
    my $self = shift;

    my $postalCode;

    if ( my $rPostalCode = $self->rPostalCode() ) {
        if ( $rPostalCode =~ /^(\d{5})-$/ ) {
            $rPostalCode = $1;
        }

        if ( my $postal = Common::Postal->new( $self->countryCode() ) ) {
            $postalCode = $postal->formatPostalCode($rPostalCode);

            if ( !$postalCode ) {
                return;

                # Rather than throwing an error, we'll just leave out the invalid zip codes.
                # We've got some Canadian ones in the mix, but no way to distinguish which country the sale is for.
                #$self->fail("Invalid postal code '$rPostalCode'");
            }
        }
    }

    return $postalCode;
}

1;
