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

package RPS::Import::Integra::v7;

use strict;

use Date::Calc qw(Days_in_Month Decode_Month);

use Carp qw(croak);

use lib '/app/tools/common/lib';
use Common::Assert;
use Common::Util qw(normalize_date);

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

use base 'RPS::Import::Integra::v6';

sub _fieldMap {
    {
        productType => 'A',
        labelName   => 'G',
        artistName  => 'H',
        albumName   => 'I',
        isrc        => 'K',
        upc         => 'K',
        trackName   => 'J',
        units       => 'M',
        price       => 'P',
    };
}

sub _unverifiedFieldMap {
    { credits => 'O', };
}

sub saleDates {
    my $self = shift;

    # from filename; see _preProcess
    return ( $self->{_startDate}, $self->{_endDate} ) if ( $self->{_startDate} );
}

sub units {
    my $self    = shift;
    my $count   = $self->_getByFieldName('units');
    my $credits = $self->_getByFieldName('credits');
    return $count + $credits;
}

sub _processSheet {
    my $self     = shift;
    my $sheet    = shift;
    my $sheetnum = shift;

    if ( $self->{sheetname} =~ /^(dist report)$/i ) {

        # Get the date information from the filename
        #
        ( $self->{_startDate}, $self->{_endDate} ) = _getDates( $self->{filename} );

        return $self->SUPER::_processSheet( $sheet, $sheetnum );
    }

    #    else { print STDERR "Skipping sheet '". $self->{sheetname} . "'\n"; }
}

sub _getDates {
    my $filename = shift;

    return undef unless ( $filename =~ m/(\d{2})-(\d{2})-(\d{2})/ );
    my ( $year, $month, $day ) = ( $1, $2, $3 );
    $year += 2000;

    my ( $dateBegin, $dateEnd, $lastDay );
    $lastDay = Days_in_Month( $year, $month );
    $dateBegin = sprintf( "%04d-%02d-%02d", $year, $month, "1" );
    $dateEnd   = sprintf( "%04d-%02d-%02d", $year, $month, $lastDay );

    print STDERR "In _getDates dateBegin: " . $dateBegin . "\n";
    print STDERR "In _getDates dateEnd: " . $dateEnd . "\n";
    return ( $dateBegin, $dateEnd );
}

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