#!/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::RoyaltyRun::Status;
use RPS::Statement::Artist::PDF;
use RPS::Statement::Mechanical::PDF;
use RPS::RoyaltyRun::Status;
use RPS::DB::Item::ArtistRoyaltyRun;
use RPS::DB::Item::MechanicalRun;
use RPS::DB::Item::ArtistRoyaltyStatement;
use RPS::DB::Item::MechanicalStatement;

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

use constant kCreateStatementScript => 'nice /app/tools/rps/bin/statements/createArtistStatementPDF.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 );

my @clientIDs;
if ( $options{clientID} ) {
    push @clientIDs, $options{clientID};
} else {
    push @clientIDs, _getLocalClientIDs();
}

foreach my $clientID (@clientIDs) {
    my $appSingleton = Common::RSApp->new( clientID => $clientID );
    report("processing client $clientID\n");
    eval {
        createAllMechanicalStatements($clientID);
        createAllArtistStatements($clientID);
    };
    if ($@) {
        report("Caught this exception: $@");
    }
}

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

sub createAllArtistStatements {
    my ($clientID) = @_;

    my $runs = RPS::DB::Item::ArtistRoyaltyRun->GetAll();

    while ( my $run = $runs->next() ) {
        report( "artist run " . $run->artist_royalty_run_id . " has status " . $run->status );

        # Only want to do this for complete, committed, or closed statements.
        #
        next
          unless ( RPS::RoyaltyRun::Status::kComplete == $run->status
            || RPS::RoyaltyRun::Status::kCommitted == $run->status
            || RPS::RoyaltyRun::Status::kClosed == $run->status );

        my $runID = $run->artist_royalty_run_id;
        my $statementsPath = RPS::Statement::Artist::PDF::StatementPathFromRunID( $runID, $clientID );

        system("/app/tools/rps/bin/statements/createAllArtistStatementsPDF.pl -c $clientID -r $runID -p $statementsPath");
    }
}

sub createAllMechanicalStatements {
    my ($clientID) = @_;

    my $runs = RPS::DB::Item::MechanicalRun->GetAll();

    while ( my $run = $runs->next() ) {
        report( "mechanical run " . $run->mechanical_run_id . " has status " . $run->status );

        # Only want to do this for complete, committed, or closed statements.
        #
        next
          unless ( RPS::RoyaltyRun::Status::kComplete == $run->status
            || RPS::RoyaltyRun::Status::kCommitted == $run->status
            || RPS::RoyaltyRun::Status::kClosed == $run->status );

        my $runID = $run->mechanical_run_id;
        my $statementsPath = RPS::Statement::Mechanical::PDF::StatementPathFromRunID( $runID, $clientID );

        system("/app/tools/rps/bin/statements/createAllMechanicalStatementsPDF.pl -c $clientID -r $runID -p $statementsPath");
    }
}

#
# Boring script stuff below...
#

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

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

    if ( defined $opt{c} ) {
        $settings->{clientID} = $opt{c};
    }

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

sub _getLocalClientIDs {

    # We have a nifty little script that will give us a list of client databases.
    #
    my $clientListString = `/app/tools/rps/bin/db/list_client_dbs.pl`;
    chomp $clientListString;

    # Find the client id that matches each database.
    #
    my @ids;
    my @dbNames = split( / /, $clientListString );
    foreach my $dbName (@dbNames) {
        my $id = Common::RSDB::DBNameToClientID($dbName);
        push @ids, $id;

    }

    return @ids;
}

