package BookPub::Import::Importer::CourseSmart::Version7;

use strict;

use Date::Calc qw(Days_in_Month);
use Data::Dumper;

use lib '/app/tools/common/lib';
use Common::Util;
use Common::Consts;
use Common::Log;

use lib '/app/tools/data_classes/lib';

use lib '/app/tools/bookpub/lib';
use BookPub::DB::Item::Sale;
use BookPub::Import::SaleRec;
use base 'BookPub::Import::Importer';

sub _fieldMap {
    {
        rPostalCode => 'U',
        dateBegin   => 'D',
        rIsbn13     => 'K',
        rIsbn10     => 'J',
        rTitle      => 'N',
        rAuthor     => 'O',
        rImprint    => 'B',
        rUnits      => 'W',
        rSales      => 'W',
        rReturns    => 'W',
        rListPrice  => 'X',
        rRevenue    => 'X',
    };
}

sub _headerIdentifier { ( dateBegin => 'Transaction Date' ) }

sub purchaseType  { BookPub::DB::Item::Sale::kPurchaseTypeLoan }
sub priceType     { 'rrp' }
sub currencyCode  { 'USD' }
sub countryCode   { 'US' }
sub productType   { BookPub::DB::Item::Sale::kProductTypeEBook }
sub _dateFormat   { [ 'numerical_year_first', 'iso' ] }
sub _useIsSaleRec { 1 }
sub rDiscount     { 0.30 }
sub rUnits        { 1 }

sub rSales {
    my $self    = shift;
    my $revenue = $self->_getByFieldName('rRevenue');

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

sub rReturns {
    my $self    = shift;
    my $revenue = $self->_getByFieldName('rRevenue');

    if ( $revenue < 0 ) {
        return 1;
    } else {
        return 0;
    }
}

sub rRevenue {
    my $self     = shift;
    my $revenue  = $self->_getByFieldName('rRevenue');
    my $discount = $self->rDiscount();

    return $revenue * ( 1 - $discount );
}

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

    if ( $code eq 'UNKNOWN' ) {
        return;
    }
    return $code;
}

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;    # Play nicely.
###
