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

package RPS::Import::V2Benelux::v1;

use strict;

use Date::Calc qw(Days_in_Month);

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

use lib '/app/tools/rps/lib';
use base 'RPS::Import::Importer';

sub _fieldMap {
    {
        # detail section of each sheet
        #
        artistName       => 'B',
        clientProductID  => 'F',
        albumName        => 'C',
        configuration    => 'G',
        sales            => 'H',
        salesRevenue     => 'A',
        totalRevenue     => 'A',

    }
}

sub _unverifiedFieldMap {
    {
        distFee => 'B',
    }
};

sub _headerIdentifier { ( albumName => 'Title' ) }

sub currencyCode { 'EUR'; }

sub physical { 1 }

sub channel { RPS::File::Sale::CHANNEL_RETAIL; }

sub priceLevel { RPS::File::Sale::PLEVEL_UNKNOWN; }

sub artistName {
    my $self = shift;
    my $name = $self->_getByFieldName('artistName');
    if( $name =~ /(\w+), (\w+)/ )
    {
        return "$2 $1";
    }
    return $name;
}

sub countryCode {
    my $self = shift;
    return $self->{_countryCode} if( $self->{_countryCode} ); # from header of current sheet; see _processSheet
}

sub saleDates {
    my $self = shift;
    return ($self->{_startDate}, $self->{_endDate}) if( $self->{_startDate} ); # from header of current sheet; see _processSheet
}

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

    if( $config =~ /^cd$/i )
    {
        return RPS::File::Sale::TYPE_CD;
    }
    elsif( $config =~ /^lp$/i || $config =~ /^12"$/i )
    {
        return RPS::File::Sale::TYPE_LP;
    }
    elsif( $config =~ /^7"$/i )
    {
        return RPS::File::Sale::TYPE_LP5;
    }

    $self->fail("Unable to determine config from format($config)");
}


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

    return ( $sales > 0 ) ? $sales : 0;
}

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

    # Apply dist fee
    #
    $self->fail( "Unable to determine distribution fee" ) unless( $self->{_distFee} );

    my $distFee = $self->{_distFee};
    $distFee = (100 - $distFee) * .01;
    $salesRevenue *= $distFee;

    return ( $salesRevenue > 0 ) ? $salesRevenue : 0;
}

sub returns {
    my $self = shift;
    my $sales = $self->_getByFieldName( 'sales' );
    my $salesRevenue = $self->_getByFieldName( 'salesRevenue' );
    return ( $sales < 0 && $salesRevenue < 0 ) ? abs($sales) : 0;
}

sub returnsRevenue {
    my $self = shift;
    my $sales = $self->_getByFieldName( 'sales' );
    my $salesRevenue = $self->_getByFieldName( 'salesRevenue' );

    # Apply dist fee
    #
    $self->fail( "Unable to determine distribution fee" ) unless( $self->{_distFee} );

    my $distFee = $self->{_distFee};
    $distFee = (100 - $distFee) * .01;
    $salesRevenue *= $distFee;

    return ( $sales < 0 && $salesRevenue < 0 ) ? abs($salesRevenue) : 0;
}

sub totalRevenue {
    my $self = shift;
    my $salesRevenue = $self->_getByFieldName( 'totalRevenue' );

    # Apply dist fee
    #
    $self->fail( "Unable to determine distribution fee" ) unless( $self->{_distFee} );

    my $distFee = $self->{_distFee};
    $distFee = (100 - $distFee) * .01;
    $salesRevenue *= $distFee;

    return $salesRevenue;
}

sub _isValidSaleRecord {
    my $self = shift;

    # The line is valid if it has sales or returns, and has an album title
    #
    return ( ($self->sales != 0 || $self->returns != 0) && $self->albumName );
}

# _processSheet is used to process a tab from the spreadsheet.  Note that we
# do not process the 'summary' tab (this is done in _preProcess).  Also, we
# invoke the inherited _processSheet so that normal line processing occurs.
#
sub _processSheet {
    my $self     = shift;
    my $sheet    = shift;
    my $sheetnum = shift;

    my %args = @_;
    if( $self->{sheetname} !~ /^summary$/ )
    {
        # Extract the territory and sales period information from the header
        #
        my $terr  = $sheet->[0][0];  # A1 - countryCode
        my $sdate = $sheet->[0][2];  # C1 - dateBegin
        my $edate = $sheet->[0][5];  # F1 - dateEnd

        # Make sure that dates encompass the entire month
        #
        if( $sdate =~ /(\d{4})-(\d{1,2})-(\d{1,2})/ ) # YYYY-MM-DD
        {
            $sdate = sprintf( "%04d-%02d-%02d", $1, $2, 1 );
            $edate = sprintf( "%04d-%02d-%02d", $1, $2, Days_in_Month($1, $2) );
        }

        # Determine the country code
        #
        my %countryMap = (
            "belgium & luxembourg" => "BE",
        );

        $terr = ( exists $countryMap{ lc $terr } ) ? $countryMap{ lc $terr } : $terr;

        my $o;
        if( $terr && $terr ne "" ) {
            $o = Common::Country->Get( $terr );
        }

        $self->{_countryCode} = (defined $o) ? $o->alpha2() : $terr;
        $self->{_startDate}   = $sdate;
        $self->{_endDate}     = $edate;
        

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

# _preProcess is called before we start processing the spreadsheet.
# Here, we're looking for the distribution fee information from the
# 'summary' tab.  Once found, we'll save it so that it can be applied
# to sales found on the sales detail tabs.
#
sub _preProcess {
    my( $self, %args) = @_;
    $self->SUPER::_preProcess(%args);
    my $fileObj = $args{file};
    $fileObj->Physical(1);

    my $sheetNames = $args{sheet_names};

    # Get the distribution fee from the summary tab
    #
    my $sheetCount = 0;
    SHEET: foreach my $sheet(@{ $args{sheets} })
    {
        my $sheetName = $sheetNames->[$sheetCount];

        next if( $sheetName !~ /^summary$/i );

        foreach my $line(@$sheet)
        {
            $self->{line} = $line;

            my $distFeeField = $self->_getByFieldName( 'distFee' );

            if( $distFeeField =~ /Distribution fee (\d{1,2})%/i )
            {
                $self->{_distFee} = $1;
                #last;
                last SHEET;
            }
        }
        $sheetCount++;
    }
}

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