#!/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::DB::Item::CAMechanicalRun;
use RPS::DB::Item::CAMechanicalStatement;
use RPS::DB::Item::CAPublisher;
use RPS::Mechanical::CA::MechanicalRun;
use RPS::Statement::Mechanical::CA::CMRRA;

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

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

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

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

sub createAllStatementsCMRRA {
    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.
    #
    my $semaphore = $outFilePath . "CMRRA_COMPLETE";
    unlink($semaphore);

    my $createdStatements = 0;

    # Get the collection of statements for this run.
    #
    my $statements = RPS::DB::Item::CAMechanicalStatement->GetByMechanicalRunID($runID);
    while ( my $statement = $statements->next() ) {

        # We only want to create these statement for agents.
        #
        my $publisherID = $statement->ca_publisher_id();
        my $publisher = RPS::DB::Item::CAPublisher->Lookup( ca_publisher_id => $publisherID );
        if ( $publisher->is_agency() == 1 ) {
            my $fileName = RPS::Statement::Mechanical::CA::CMRRA->StatementFileNameFromDBItem($statement);

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

    if ( $createdStatements == 1 ) {

        # Create the semaphore if we created any statements
        #
        open SEMAPHORE, "> $semaphore";
        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 <ca_mechanical_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 <ca_mechanical_royalty_run_id>\tThe id of the ca mechanical 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";
    }
}

