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

package RPS::Import::PIAS::v2;

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 {
    {
        # summary sheet
        #
        dateBegin => 'A',

        # detail sheet
        #
        artistName     => 'D',
        albumName      => 'C',
        totalRevenue   => 'K',
        countryCode    => 'E',
        wholesalePrice => 'G',
    };
}

sub _unverifiedFieldMap {
    {
        quantity     => 'F',    # can be sales or returns
        supplierCode => 'B',
    };
}

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

sub currencyCode { 'EUR'; }

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

sub priceLevel { RPS::File::Sale::PLEVEL_FULL }

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

sub artistName {
    my $self = shift;
    my $name = $self->_getByFieldName('artistName');
    $name =~ s/^-   //;                                                              # Remove any cruft if necessary
    return $name;
}

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

    # %countryMap contains mappings of non-standard country names
    # to a valid country codes.
    #
    my %countryMap = ( 'swiss' => 'CH', );

    $cname = $countryMap{ lc $cname } || $cname;

    my $countryObj = Common::Country->Get($cname);
    my $countryCode = $countryObj->alpha2() if ($countryObj);
    return $countryCode;
}

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

    if ( $config =~ /lp$/i ) {
        return RPS::File::Sale::TYPE_LP;
    } elsif ( $config =~ /cdx$/i ) {
        return RPS::File::Sale::TYPE_CD;
    }

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

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

    if (   $config =~ /(lp)$/i
        || $config =~ /(cdx)$/i ) {
        return $1;
    }

    $self->fail("Unable to determine configuration from supplier code($config)");
}

sub sales {
    my $self         = shift;
    my $quantity     = $self->_getByFieldName('quantity');
    my $price        = $self->_getByFieldName('wholesalePrice');
    my $grossRevenue = $quantity * $price;

    return ( $grossRevenue > 0 ) ? $quantity : 0;
}

sub salesRevenue {
    my $self = shift;

    my $quantity     = $self->_getByFieldName('quantity');
    my $price        = $self->_getByFieldName('wholesalePrice');
    my $grossRevenue = $quantity * $price;

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

    return ( $grossRevenue > 0 ) ? $totalRevenue : 0;
}

sub returns {
    my $self         = shift;
    my $quantity     = $self->_getByFieldName('quantity');
    my $price        = $self->_getByFieldName('wholesalePrice');
    my $grossRevenue = $quantity * $price;

    return ( $grossRevenue < 0 ) ? abs($quantity) : 0;
}

sub returnsRevenue {
    my $self         = shift;
    my $quantity     = $self->_getByFieldName('quantity');
    my $price        = $self->_getByFieldName('wholesalePrice');
    my $grossRevenue = $quantity * $price;

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

    return ( $grossRevenue < 0 ) ? abs($totalRevenue) : 0;
}

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 && $self->albumName ne '===============' );
}

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

    my $sheetNames = $args{sheet_names};

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

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

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

            my $date = $self->_getByFieldName('dateBegin');

            #                               DD         MM       YYYY         DD         MM       YYYY
            if ( $date =~ /for the period (\d{1,2})\/(\d{1,2})\/(\d{4}) to (\d{1,2})\/(\d{1,2})\/(\d{4})/ ) {
                $self->{_startDate} = sprintf( "%04d-%02d-%02d", $3, $2, $1 );
                $self->{_endDate}   = sprintf( "%04d-%02d-%02d", $6, $5, $4 );
                last SHEET;
            }
        }
        $sheetCount++;
    }
}

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