package RPS::Import::MusicUnlimited::v1;

use strict;

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

use lib '/app/tools/common/lib';
#use Common::Util qw(normalize_date normalize_upc);
use Common::Country;

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

use lib '/app/tools/rps/lib';
use RPS::File::Sale;
use RPS::Import::ServiceMap;

use base 'RPS::Import::Importer';

# non-standard _fieldMap; need to override _importLines
sub _fieldMap {
    {
        labelName     => 'R',
        countryCode   => 'C',
        dateBegin     => 'G',
        dateEnd       => 'H',
        artistName    => 'J',
        upc           => 'L',
        isrc          => 'I',
        trackName     => 'K',
        albumName     => 'N',
        units         => 'P',
        #currencyCode  => 'Y',
        price         => 'Z',
    }
}

sub _unverifiedFieldMap {
    {
        altLabelName  => 'Q',
        footerLabel   => 'AA',
    }

}

sub _headerIdentifier { ( dateBegin => 'Sales period begin' ) }

sub productType { RPS::File::Sale::TYPE_TRACK; }

sub formatType { RPS::File::Sale::FORMAT_STREAM; }

sub currencyCode { 'USD' }

sub labelName
{
    my $self = shift;
    my $label = $self->_getByFieldName('labelName');
    $label = $self->_getByFieldName('altLabelName') if( !$label );
    return $label;
}

sub price
{
    my $self = shift;
    my $fullPrice = $self->_getByFieldName('price');

    my $fee = 1 - $self->{_adminfee};  # Return the royalty minus the admin fee
    my $net = $fullPrice * $fee;
    return $net;
}

# Find the admin fee in the footer; we'll use this to adjust the net price read
# in from each line.
#
sub _preProcess
{
    my $self = shift;
    my %args = @_;
    Log->info( "Starting _preProcess" );
    $self->SUPER::_preProcess(%args);

    my $totalRevenue;
    my $netRevenue;
    my $adminFee;
    my $linenum = 1;
    foreach my $line(@{ $args{lines} })
    {
        $self->{line} = $line;

        my $footerLabel = $self->_getByFieldName('footerLabel');

        if( $footerLabel eq 'TOTAL' )
        {
            $totalRevenue  = $self->_getByFieldName('price');
            print STDERR "_preProcess: Line $linenum: Found TOTAL $totalRevenue\n";
        }

        if( $footerLabel =~ m/NET DUE/ )
        {
            $netRevenue = $self->_getByFieldName('price');
            print STDERR "_preProcess: Line $linenum: Found NET REVENUE $netRevenue\n";
        }

        last if ( defined $totalRevenue && defined $netRevenue);

        $linenum++;
    }

    # Calculate the admin fee if netRevenue and totalRevenue are present, otherwise
    # the user will have to enter the fee manually through the UI.
    #
    $adminFee = ( $totalRevenue && $netRevenue ) ? (1 - ($netRevenue / $totalRevenue)) : 0;

    $self->{_adminfee} = $adminFee;
}

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