package BookPub::Import::Importer::IndianaUniversity;

use strict;
use Data::Dumper;

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

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

sub _fieldMap {
    my $self = shift;

    my %fieldMap = (
        1 => {
            rAuthor    => 'J',
            rTitle     => 'I',
            rIsbn13    => 'H',
            rReturns   => 'P',
            rSales     => 'O',
            rUnits     => 'Q',
            rUnitPrice => 'N',
            rListPrice => 'M',
            rRevenue   => 'R',
        },
        2 => {
            rAuthor      => 'J',
            rTitle       => 'I',
            rIsbn13      => 'H',
            rReturns     => 'Q',
            rSales       => 'P',
            rUnits       => 'S',
            rAdjustments => 'U',
            rUnitPrice   => 'N',
            rListPrice   => 'M',
            rRevenue     => 'V',
        },
    );

    return $fieldMap{ $self->_version() };
}

sub purchaseType       { BookPub::DB::Item::Sale::kPurchaseTypeSubscriptionDL }
sub productType        { BookPub::DB::Item::Sale::kProductTypeEBook }
sub priceType          { 'rrp' }
sub rInstitution       { 'Indiana University' }
sub rListPriceCurrency { 'USD' }
sub currencyCode       { 'USD' }
sub countryCode        { 'US' }

sub _dateFormat { [ 'us', 'iso' ] }
sub _autoParseTitleAndSubtitle { 1 }
sub _useIsSaleRec              { 1 }

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

    if (   !$self->rAuthor()
        && !$self->rTitle()
        && !$self->rIsbn13()
        && !$self->rSales()
        && !$self->rReturns()
        && !$self->rUnitPrice()
        && !$self->rListPrice() ) {

        $self->{_endOfData} = 1;
        return;
    }

    return $self->SUPER::_processLine(@_);
}

sub _isSaleRec {
    my $self = shift;

    # If we've set the end of data flag in processLine, we are done.
    return if ( $self->{_endOfData} );

    return if ( $self->rUnits == 0 && $self->rRevenue == 0 );

    return $self->SUPER::_isSaleRec();
}

# client wishes to have the file upload date as the transaction date for all sales
sub dateBegin {
    my $self = shift;
    my $date = $self->_getByFieldName('dateBegin');

    return substr( $self->{_file}{DateCreated}{_value}, 0, 10 );
}

sub rTransactionCategory {
    my $self = shift;
    my $seasonYear;
    my $filename = $self->filename();

    if ( $filename =~ /(Spring|Summer|Fall|Winter) (\d{4})/i ) {
        $seasonYear = $1 . " " . $2;
    } else {
        $self->fail("Cannot find a season/year combination in filename: $filename");
    }

    return $seasonYear;

}

1;
