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

package RPS::ArtistRoyalty::Fast::Script::CustomStatementSummary;

use strict;
use Data::Dumper;
use File::Path;

use lib '/app/tools/common/lib';
use lib '/app/tools/rps/lib';
use lib '/app/tools/raptor/lib';


use Common::Log;

use RPS::DB::Item::ArtistRoyaltyExpenseItem;
use RPS::DB::Item::ArtistRoyaltyIncomeItem;
use RPS::DB::Item::ArtistRoyaltyLicenseIncomeItem;
use RPS::DB::Item::ArtistRoyaltyStatement;

use base 'Common::Script';

sub _options {
    {
        client_id => {
            short       => 'c',
            required    => 1,
            description => 'Limit to this client id',
            parameter   => 'i'
        },
        run_id => {
            short       => 'r',
            required    => 1,
            description => 'artist_royalty_run_id to process',
            parameter   => 'i'
        },
    };
}

sub _process {
    my ($self) = @_;

    Log->info('Custom Statement Summary - starting');

    my $runID = $self->param('run_id');

    # We need to loop over the statements in this run and fill in 6 new columns
    my $statements = RPS::DB::Item::ArtistRoyaltyStatement->Get( runID => $runID );

    if ($statements) {
        while ( $statements->hasNext() ) {
            my $statement = $statements->next();
            my $statementID = $statement->artist_royalty_statement_id;

            # income totals
            my ( $netSalesTotal, $salesTotal) = RPS::DB::Item::ArtistRoyaltyIncomeItem->GetTotalsByStatementID( $statementID );
            $statement->net_sales_total($netSalesTotal);
            $statement->sales_total($salesTotal);

            # license income totals
            my ( $licenseIncomeSalesTotal, $licenseIncomeTotal) = RPS::DB::Item::ArtistRoyaltyLicenseIncomeItem->GetTotalsByStatementID( $statementID );
            $statement->license_income_sales_total($licenseIncomeSalesTotal);
            $statement->license_income_total($licenseIncomeTotal);

            # expense totals (we'll go ahead and make these negative for the report)
            my ( $expenseAmountTotal, $expenseEffectiveAmountTotal) = RPS::DB::Item::ArtistRoyaltyExpenseItem->GetTotalsByStatementID( $statementID );
            $statement->expense_amount_total(-1 * $expenseAmountTotal);
            $statement->expense_effective_amount_total(-1 * $expenseEffectiveAmountTotal);

            $statement->save();
        }
    }

    Log->info('Custom Statement Summary - done');
}

1;
