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

package RPS::LabelRoyalty::Fast::Script::RunLabelRoyalties;

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 DB_File;

use Common::Log;

use Common::RSApp;
use RPS::DB::Item::LabelRoyaltyRun;
use RPS::RoyaltyRun::Status;
use RPS::Statement::Label::PDF;
use RPS::LabelRoyalty::Job::CreatePDFStatements;


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 => 'The label_royalty_run_id we are creating statements for.',
        parameter   => 'i',
    },
    verbosity =>
    {
        short       => 'V',
        required    => 0,
        description => 'Specify log level, old style',
        parameter   => 'i',
    },
}}



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

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

    Log->warn("Beginning royalty run $runID");

    # Read in the run record, so we can get the correct payor_id.
    #
    my $runData = RPS::DB::Item::LabelRoyaltyRun->Lookup(label_royalty_run_id => $runID);
    die "ERROR - invalid run id $runID" unless $runData;


    # JPK - For now, we'll assume that we're going to run everything on a single host.
    #

    # !!! These values should probably come from the config file system, but for the moment
    # !!! I will hard-code them.
    #
    my $staticDataPath = "/app/data/label_royalty_run/".Common::RSApp::GetClientID()."/".$runID;
    my $outputDataPath = $staticDataPath . "/output";


    eval {
        $self->_runRoyalties($runData, $staticDataPath, $outputDataPath);
    };
    if ($@)
    {
        $runData->status(RPS::RoyaltyRun::Status::kError);
#        $runData->error($@);
        $runData->end_time(Common::DB::Item::kDateTimeNow);
        Log->crit($@);
        $runData->save();
    }

    Log->warn("Finished royalty run $runID");
    
}

sub _runRoyalties
{
    my ($self, $runData, $staticPath, $outputPath) = @_;


    my $binDir = '/app/tools/rps/lib/RPS/LabelRoyalty/Fast/bin';

    $runData->status(RPS::RoyaltyRun::Status::kRunning);
    $runData->start_time(Common::DB::Item::kDateTimeNow);
    $runData->pid($$);
    $runData->save();

    my $runID = $runData->label_royalty_run_id();
    my $clientID = Common::RSApp::GetClientID();
    my $salesMapProcessCount = 12;

    my @commands = (
        "$binDir/stageData.pl -c $clientID -r $runID -d $staticPath",
        "$binDir/mapPayees.pl  -c $clientID -d $staticPath -o $outputPath",
        "$binDir/mapSales.pl  -c $clientID -d $staticPath -o $outputPath -p$salesMapProcessCount",
        "$binDir/mapTransactions.pl  -c $clientID -d $staticPath -o $outputPath -vvv",
        "sort -s -t'" . "\t" . "' -k1,1n -k2,2n -k3,3n -k4,4n -k29,29n -k8,8n -k7,7n -k12,12 -k9,9 -k10,10 -k23,23 -k24,24n -k25,25n -k19,19 -k20,20 -k11,11n -k21,21 -k13,13n -k14,14n -k15,15n -k16,16n -k17,17 $outputPath/mapped_data_* > $outputPath/mapped_data.sorted",
        "$binDir/assembleStatements.pl -c $clientID -r $runID -s $staticPath -o $outputPath",
        "$binDir/commitFinalData.pl -c $clientID -r $runID -o $outputPath",

#        "$binDir/mapReserves.pl -c $clientID -d $staticPath -o $outputPath",
#        "$binDir/mapExpenses.pl -c $clientID -d $staticPath -o $outputPath",
#        "$binDir/mapLicenseIncomeSales.pl  -c $clientID -d $staticPath -o $outputPath",
#        "$binDir/mapPendingTransactions.pl  -c $clientID -d $staticPath -o $outputPath",
#        "$binDir/mapPayees.pl  -c $clientID -d $staticPath -o $outputPath",
#        "$binDir/mapAlbumContractAccounts.pl  -c $clientID -d $staticPath -o $outputPath",
#        'sort -n -t$'."'\t' -k1 -k2 -k3 -k4 $outputPath/missed_sales_* > $outputPath/missed_sales.sorted",
#        "$binDir/assembleMissedSaleLog.pl -c $clientID -r $runID -d $staticPath -o $outputPath",
    );

    foreach my $cmd (@commands)
    {
        Log->warn("executing: $cmd");
        my $status = system($cmd);
        die "ERROR EXECUTING '$cmd': ($?) $!" unless 0 == $status;
    }

    $runData->status(RPS::RoyaltyRun::Status::kComplete);
    $runData->end_time(Common::DB::Item::kDateTimeNow);
    $runData->save();


    # Finally, queue up the job to create PDF statements.
    #
    my $statementPath = RPS::Statement::Label::PDF::StatementPathFromRunID($runID, $clientID);
    if (! -d $statementPath)
    {
        mkpath($statementPath) or die "ERROR: Unable to create path $statementPath: $!\n";
    }

    my $jobArgs = RPS::LabelRoyalty::Job::CreatePDFStatements->new
    (
        runID => $runID,
        clientID => $clientID,
        filePath => $statementPath,
    );
    my $job = $jobArgs->enqueue();
}

1;
