package BookPub::Import::Importer::Follett_Higher_Education::Version11;

use strict;

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

sub _fieldMap {
    {
        dateBegin            => 'F',
        rAuthor              => 'N',
        rTitle               => 'O',
        rIsbn13              => 'K',
        rInstitution         => 'R',
        rState               => 'T',
        rPostalCode          => 'U',
        rListPrice           => 'Y',
        rRevenue             => 'Z',
        rDeliveryMethod      => 'Q',
        rChannel             => 'E',
        rTransactionCategory => 'V',
    };
}

sub rListPriceCurrency { 'USD' }

sub units {
    my $self = shift;

    if ( $self->revenue() >= 0 ) {
        return 1;
    } else {
        return -1;
    }
}

# For this importer, we'll determine the country by the value of the state column
sub countryCode {
    my $self        = shift;
    my $rState      = $self->rState();
    my $postalObjUS = Common::Postal->new('US');
    my $postalObjCA = Common::Postal->new('CA');

    # US state abbreviation
    if ( $postalObjUS->getName($rState) || !defined $rState || $rState eq '(blank)' ) {
        return "US";

        # CA state abbreviation
    } elsif ( $postalObjCA->getName($rState) ) {
        return "CA";
    } else {
        $self->fail("State is neither a valid US state or Canadian province: $rState");
    }
}

sub state {
    my $self = shift;
    my $state;
    my $countryCode = $self->countryCode();
    my $postalObj   = Common::Postal->new($countryCode);

    if ( my $rState = $self->rState() ) {
        if ( $countryCode eq "US" ) {
            if ( $postalObj->getName($rState) ) {

                # acceptable state abbreviation
                $state = $rState;
            }
        } elsif ( $countryCode eq "CA" ) {
            if ( $postalObj->getName($rState) ) {

                # acceptable province abbreviation
                $state = $rState;
            }
        } else {
            $self->fail("Invalid country code: $countryCode");
        }
    }
    return $state;
}

sub rPostalCode {
    my $self = shift;
    my $code = $self->SUPER::rPostalCode();

    # Sales files for this importer sometimes have a "0" for a postal code,
    # we are treating that as a NULL value
    if ( $code eq '0' ) {
        return;
    }
    return $code;
}

sub postalCode {
    my $self = shift;
    my $postalCode;
    my $rPostalCode = $self->rPostalCode();

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

            if ( !$postalCode ) {
                return;
            }
        }
    }

    return $postalCode;
}

1;
