package RPS::Import::EMIMusic::Subscriptions::v2;

use strict;

use lib '/app/tools/data_classes/lib';
use lib '/app/tools/common/lib';
use lib '/app/tools/rps/lib';
use lib '/app/tools/raptor/lib';
use Common::Date;
use Common::Log;
use Common::RSMath;
use Client::Service;

use base 'RPS::Import::EMIMusic::Subscriptions::v1';

use Data::Dumper;

sub _importLines {
    my ( $self, %args ) = @_;

    # We're going to collect header statistics.
    # If the header doesn't match correctly, we croak.
    #

    my $rVal = $self->SUPER::_importLines(%args);

    # Sanity-check the last block.
    #
    $self->_checkStreamCount();

    if ( $self->{_badBlocks} > 0 ) {

        # JPK - We could just call die here, but that will tack on the file name/line num stuff that we frankly don't need to report.
        #
        $self->errstr( "Header unit totals do not match detail unit totals for "
              . $self->{_badBlocks}
              . " out of "
              . $self->{_totalBlocks}
              . " headers." );
        return undef;
    }

    return $rVal;
}

sub _checkStreamCount {
    my ($self) = @_;

    if ( $self->{_expectedStreamCount} ) {
        Common::Log::Print( "expected: " . $self->{_expectedStreamCount} . ", actual: " . $self->{_actualStreamCount} );
        if ( $self->{_actualStreamCount} != $self->{_expectedStreamCount} ) {
            $self->{_badBlocks}++;
        }
    }
}

sub _processNewHeader {
    my ($self) = @_;

    $self->_checkStreamCount();

    my $streams = $self->_getByFieldName('streamCount');
    $self->{_expectedStreamCount} = $streams;
    $self->{_actualStreamCount}   = 0;
    $self->{_totalBlocks}++;

    $self->SUPER::_processNewHeader();
}

# I'll override this to count the accumulated units.
#
sub _validateUnits {
    my ( $self, $saleRec ) = @_;
    $self->SUPER::_validateUnits($saleRec);

    my $units = $saleRec->units;
    $self->{_actualStreamCount} += $units;
}

###
1;    # Play nicely.
###
