#---------------------------------------------------------------
# ____                   _ _         ____  _
#|  _ \ ___  _   _  __ _| | |_ _   _/ ___|| |__   __ _ _ __ ___
#| |_) / _ \| | | |/ _` | | __| | | \___ \| '_ \ / _` | '__/ _ \
#|  _ < (_) | |_| | (_| | | |_| |_| |___) | | | | (_| | | |  __/
#|_| \_\___/ \__, |\__,_|_|\__|\__, |____/|_| |_|\__,_|_|  \___|
#            |___/             |___/
#
# Copyright (C) 2015 RoyaltyShare, Inc.   All Rights Reserved
#---------------------------------------------------------------

package RPS::Import::Caroline::v13;

use strict;

use Date::Calc qw(Days_in_Month Decode_Month);

use lib '/app/tools/common/lib';
use Common::Assert;

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

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

sub _fieldMap {
    my $self = shift;
    my $version = $self->_version;

    my %field_map = (
        13 => {
            # header
            currencyCode     => 'R',

            # detail
            productType      => 'K',
            artistName       => 'F',
            upc              => 'G',
            albumName        => 'H',
            units            => 'U',
            totalRevenue     => 'R',
        },
    );
    return $field_map{$version};
}

sub _unverifiedFieldMap {
    my $self = shift;
    my $version = $self->_version;

    my %field_map = (
        13 => {
            calYear          => 'B',
            calMonth         => 'C',
            netQuantity      => 'U',
            netSales         => 'R',
        },
    );
    return $field_map{$version};
}

sub _headerIdentifier { ( upc => 'CPRS new UPC code' ) }
sub physical { 1 }
sub channel { RPS::File::Sale::CHANNEL_RETAIL }
sub priceLevel { RPS::File::Sale::PLEVEL_UNKNOWN }

sub countryCode {
    my $self = shift;
    $self->{_countryCode}; # From filename -- see _preProcess()
}

sub currencyCode {
    my $self = shift;
    $self->{_currencyCode}; # From header -- see _preProcess()
}


sub productType {
    my $self = shift;
    my $type = $self->_getByFieldName('productType');

    if( $type =~ /^cd album$/i )
    {
        return RPS::File::Sale::TYPE_CD;
    }
    elsif( $type =~ /^vinyl album 12\" 33 rpm$/i )
    {
        return RPS::File::Sale::TYPE_LP;
    }

    $self->fail("Unable to determine product type from '$type'");
}


sub saleDates {
    my $self  = shift;
    my $year  = $self->_getByFieldName('calYear');
    my $month = $self->_getByFieldName('calMonth');
    my $dateBegin = sprintf("%04d-%02d-%02d", $year, $month, 1);
    my $dateEnd   = sprintf("%04d-%02d-%02d", $year, $month, Days_in_Month($year, $month) );
    return ($dateBegin, $dateEnd);
}

sub units {
    my $self = shift;
    my $units   = $self->_getByFieldName('netQuantity');
    my $revenue  = $self->_getByFieldName('netSales');

    # follow the money...
    # if sign of units and revenue differ, flip the units to match revenue
    if( $units < 0 && $revenue > 0 ) { $units = abs($units) }
    if( $units > 0 && $revenue < 0 ) { $units = -1 * abs($units) }

    return $units;
}

sub sales {
    my $self = shift;
    my $units   = $self->_getByFieldName('netQuantity');
    my $revenue  = $self->_getByFieldName('netSales');

    # follow the money...
    # if sign of units and revenue differ, flip the units to match revenue
    if( $units < 0 && $revenue > 0 ) { $units = abs($units) }
    if( $units > 0 && $revenue < 0 ) { $units = -1 * abs($units) }

    return ($units >= 0 && $revenue > 0 ) ? $units : 0;
}

sub salesRevenue {
    my $self = shift;
    my $revenue  = $self->_getByFieldName('netSales');
    return ($revenue >= 0 ) ? $revenue : 0;
}

sub returns {
    my $self = shift;
    my $units   = $self->_getByFieldName('netQuantity');
    my $revenue  = $self->_getByFieldName('netSales');

    # follow the money...
    # if sign of units and revenue differ, flip the units to match revenue
    if( $units < 0 && $revenue > 0 ) { $units = abs($units) }
    if( $units > 0 && $revenue < 0 ) { $units = -1 * abs($units) }

    return ($revenue < 0 ) ? abs($units) : 0; # Follow the sign of the revenue
}

sub returnsRevenue {
    my $self = shift;
    my $revenue  = $self->_getByFieldName('netSales');
    return ($revenue < 0) ? abs($revenue) : 0;
}

sub free {
    my $self = shift;
    my $totalRevenue  = $self->_getByFieldName('netSales');
    my $units   = $self->_getByFieldName('netQuantity');
    return 1 if( $totalRevenue == 0 && $units != 0 );
}

sub _preProcess {
    my $self = shift;
    my %args = @_;
    $self->SUPER::_preProcess( %args );

    $self->{_countryCode} = 'CA' if( $self->filename =~ /[_ ]CA[_ ]/i );
    $self->{_currencyCode} = 'CAD' if( $self->filename =~ /[_ ]CA[_ ]/i );
}

sub _isValidSaleRecord {
    my $self = shift;
    my $units   = $self->_getByFieldName('netQuantity');
    my $revenue  = $self->_getByFieldName('netSales');

    # we want to error out when we have revenue but no units
    if( $units == 0 && $revenue != 0 ) { 
        if( $self->albumName ) {
            $self->fail("Bad input, revenue ($revenue) but no units ($units)");
        } else {
            return 0;
        }
    }

    # The line is valid if it has revenue (both sales and return are in the
    # same column, and has an album title
    #
    return ( $self->albumName && $revenue != 0 );
}

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