package BookPub::Import::Importer::APUS;

use strict;

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

sub _headerIdentifier { shift->_version() == 1 ? ( rTitle => 'Course Material Title' ) : ( rTitle => 'Title' ) }

sub _fieldMap {
    my $self = shift;

    my %fieldMap = (
        1 => {
            dateBegin  => 'B',
            dateEnd    => 'C',
            rTitle     => 'F',
            rUnitPrice => 'G',
            rListPrice => 'G',
            rRevenue   => 'J',
        },
        2 => {
            dateBegin  => 'B',
            dateEnd    => 'C',
            rTitle     => 'F',
            rUnits     => 'H',
            rUnitPrice => 'G',
            rListPrice => 'G',
            rRevenue   => 'I',
        },
    );

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

sub _unverifiedFieldMap {
    my $self = shift;

    my %fieldMap = (
        1 => {
            sessionName    => 'E',
            statesideUnits => 'H',
            overseasUnits  => 'I',
        },
        2 => {
            sessionName => 'E',
        },
    );

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

sub purchaseType { BookPub::DB::Item::Sale::kPurchaseTypeSubscriptionDL }
sub productType  { BookPub::DB::Item::Sale::kProductTypePhysicalBook }
sub priceType    { 'rrp' }

sub rListPriceCurrency { 'USD' }
sub currencyCode       { 'USD' }
sub countryCode        { 'US' }

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

sub _validTabNames { ['BILLING'] }

sub rUnits {
    my $self = shift;
    my $units;

    if ( $self->_fieldMap()->{'rUnits'} ) {
        $units = $self->SUPER::rUnits();
    } else {
        my $stateside = $self->_getByFieldName('statesideUnits');
        my $overseas  = $self->_getByFieldName('overseasUnits');

        $units = $stateside + $overseas;
    }

    return $units;
}

sub _processLine {
    my $self      = shift;
    my $totalLine = $self->_getByFieldName('sessionName');

    # an invalid tab has the "Totals" line in it, so endOfData was being
    # set prematurely.  Check that a tab is valid before setting EOD
    if ( $totalLine =~ /Total by Publisher/i && $self->_isValidTab() ) {
        $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 undef unless $self->_isValidTab();

    return if ( !$self->dateBegin()
        && !$self->dateEnd()
        && !$self->rUnitPrice()
        && !$self->rListPrice()
        && !$self->rRevenue() );

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

sub _isValidTab {
    my $self = shift;

    my $validTab;
    my $validTabNames = _validTabNames();
    foreach my $validTabName (@$validTabNames) {
        if ( $self->sheetname() =~ /$validTabName/i ) {
            $validTab = 1;
        }
    }

    return $validTab;
}

1;
