#!/usr/bin/perl
#------------------------------------------------------------
# Copyright (C) 2013 RoyaltyShare, Inc.   All Rights Reserved
# $Id$
#------------------------------------------------------------
use strict;

#use warnings;

use File::Path;
use Data::Dumper;
use Getopt::Std;
use Carp;

use lib '/app/tools/common/lib';
use Common::Assert;
use Common::Util;

use lib '/app/tools/rps/lib';
use RPS::Statement::Artist::Excel;
use RPS::ArtistRoyalty::ArtistRoyaltyRun;
use RPS::RoyaltyRun::Status;
use RPS::DB::Item::ArtistRoyaltyRun;
use RPS::DB::Item::ArtistRoyaltyStatement;
use RPS::DB::Item::ArtistPayee;

$SIG{__DIE__} = \&Carp::confess;

use constant kCreateStatementScript => 'nice /app/tools/rps/bin/statements/createArtistStatementExcel.pl';

# This determines how much output we spew forth to STDERR.
# The user can set this with the -V command-line argument.
#
my $gVerbosityLevel = 1;

# Parse the command-line, then create the statements
#
my %options;
parseCommandLine( \%options );

createAllStatementsExcel( $options{clientID}, $options{runID}, $options{outputPath} );

# ----------------------------------------------------------------------------------------------

sub createAllStatementsExcel {
    my ( $clientID, $runID, $outFilePath ) = @_;

    # Instantiate the application singleton object.
    #
    my $appSingleton = Common::RSApp->new( clientID => $clientID );

    # Create the output path, if it isn't there already.
    #
    if ( '/' ne substr( $outFilePath, -1, 1 ) ) {
        $outFilePath .= '/';
    }
    if ( !-d $outFilePath ) {
        mkpath($outFilePath) or die "ERROR: Unable to create path $outFilePath: $!\n";
    }

    # Get rid of the semaphore file(s).
    #
    my $semaphore = $outFilePath . "EXCEL_COMPLETE";
    unlink($semaphore);

    my $committedSemaphore = $semaphore . "_COMMITTED";
    unlink($committedSemaphore);

    # Get the collection of statements for this run.
    #
    my $statements = RPS::DB::Item::ArtistRoyaltyStatement->GetByArtistRoyaltyRunID($runID);
    while ( my $statement = $statements->next() ) {
        my $fileName = RPS::Statement::Artist::Excel::StatementFileNameFromDBItem($statement);

        # Invoke another script to create the actual Excel doc.
        #
        my $statementID = $statement->artist_royalty_statement_id;
        my $outputFile  = $outFilePath . $fileName;
        my $command     = kCreateStatementScript . " -s $statementID -c $clientID -f $outputFile";
        my $exitCode    = system($command);
    }

    # Create the semaphore
    #
    open SEMAPHORE, "> $semaphore";
    print SEMAPHORE "done\n";
    close SEMAPHORE;

    # If the state of the run is 'COMMITTED' or 'CLOSED', then we want to
    # add an extra semaphore to note that these statements are ready for the portal.
    #
    my $run = RPS::ArtistRoyalty::ArtistRoyaltyRun->new( artistRoyaltyRunID => $runID, loadSubs => 0 );
    if (   RPS::RoyaltyRun::Status::kCommitted == $run->Status()
        || RPS::RoyaltyRun::Status::kClosed == $run->Status() ) {
        open SEMAPHORE, "> $committedSemaphore";
        print SEMAPHORE "done\n";
        close SEMAPHORE;
    }
}

#
# Boring script stuff below...
#

sub parseCommandLine {
    my ($settings) = @_;

    my %opt;
    getopts( 'r:c:p:V:', \%opt );

    if ( !$opt{r} || !$opt{c} || !$opt{p} ) {
        usage();
        exit(1);
    }
    $settings->{runID}      = $opt{r};
    $settings->{clientID}   = $opt{c};
    $settings->{outputPath} = $opt{p};

    if ( defined $opt{V} ) {
        $gVerbosityLevel = $opt{V};
    }
}

sub usage {
    print STDERR "\nusage: $0 -c <client_id> -r <artist_royalty_run_id> -p <output path>\n";
    print STDERR "\n";
    print STDERR "Arguments:\n";
    print STDERR "\t-c <client_id>\t\t\tThe client_id of the client to process\n";
    print STDERR "\t-r <artist_royalty_run_id>\tThe id of the artist royalty run\n";
    print STDERR "\t-p <output path>\t\tThe path to where we'll be saving these files\n";
}

sub report {
    my ( $string, $verbosity ) = @_;
    $verbosity = 1 unless defined $verbosity;

    if ( $gVerbosityLevel >= $verbosity ) {
        print STDERR $string . "\n";
    }
}

