#!/usr/bin/perl
#------------------------------------------------------------
# Copyright (C) 2006 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::PDF;
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/createArtistStatementPDF.pl';
use constant kCreateStatementChineseScript => 'nice /app/tools/rps/bin/statements/createArtistStatementChinesePDF.pl';
use constant kCreateStatementEmbededFontScript => 'nice /app/tools/rps/bin/statements/createArtistStatementEmbededFontPDF.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 PDF!
#
my %options;
parseCommandLine( \%options );

createAllStatementsPDF( $options{clientID}, $options{runID}, $options{mode}, $options{outputPath} );

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

sub createAllStatementsPDF {
    my ( $clientID, $runID, $mode, $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) related to the statement type(s) that
    # we'll be generating.
    #

    # The COMPLETE and COMPLETE_COMMITTED semaphores are used for payee statements
    my $semaphore = $outFilePath . "COMPLETE";
    unlink($semaphore) if ($mode eq 'b' || $mode eq 'p');

    my $committedSemaphore = $semaphore . "_COMMITTED";
    unlink($committedSemaphore) if ($mode eq 'b' || $mode eq 'p');


    # The FULL_COMPLETE semaphore is used for full label-view statements
    my $fullSemaphore = $outFilePath . "FULL_COMPLETE";
    unlink($fullSemaphore) if ($mode eq 'b' || $mode eq 'f');


    # 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::PDF::StatementFileNameFromDBItem($statement);

        # Invoke another script to create the actual pdf document(s)
        #
        my $statementID = $statement->artist_royalty_statement_id;
        my $outputFile  = $outFilePath . $fileName;

        # Some clients require generating statements in either Chinese or Cyrillic
        # 607 = Media Asia (Chinese)
        # 510 = Virginia Records (Cyrillic)
        # 621 = MDLBeast (Arabic)
        my $command = kCreateStatementScript . " -s $statementID -c $clientID -f $outputFile -m $mode";
        if ( $clientID =~ /^(607)$/ ) {
            $command = kCreateStatementChineseScript . " -s $statementID -c $clientID -f $outputFile -m $mode";
        } elsif ( $clientID =~ /^(510|621|)$/ ) {
            $command = kCreateStatementEmbededFontScript . " -s $statementID -c $clientID -f $outputFile -m $mode";
        }

        my $exitCode = system($command);
    }

    # Create the semaphore(s)
    #
    if ($mode eq 'b' || $mode eq 'p') {
        open SEMAPHORE, "> $semaphore";
        print SEMAPHORE "done\n";
        close SEMAPHORE;
    }

    if ($mode eq 'b' || $mode eq 'f') {
        open SEMAPHORE, "> $fullSemaphore";
        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 payee statements are ready
    # for the portal.
    #
    if ($mode eq 'b' || $mode eq 'p') {
        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:m:', \%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};
    }

    if ( defined $opt{m} )
    {
        if ( $opt{m} =~ /^(F|P|B).*$/i ) {
            $settings->{mode} = lc $1;
        } else {
            usage();
            exit(1);
        }
    } else {
        $settings->{mode} = 'b';  # default to both full and payee views
    }

}

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";
    }
}

