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

use Getopt::Std;

use lib '/app/tools/common/lib';
use lib '/app/tools/bookpub/lib';
use BookPub::Sale::Report::Reconciliation;

#use BookPub::Sale::Report::Royalty;
use BookPub::Tracker::File;

use Common::NumericFormat;
use Common::Log;
use Common::RSApp;

# Allow tuning of the verbosity of our output.
#
my $gVerbosityLevel = 1;

#$|++;
#open(STDERR, ">>/app/shared/sale_report/report.log") unless (-t STDIN && -t STDOUT);
Common::Log::Print(" - running with args '@ARGV'");

my %opt;
getopts( 'p:c:a:re', \%opt );

my $client_id = $opt{c};
my $period_id = $opt{p};
my $atomic    = $opt{a};

usage("missing client_id") unless ( defined $client_id );
usage("missing period_id") unless ( defined $period_id );

my $appSingleton = Common::RSApp->new( clientID => $client_id );

gen_recon( $client_id, $period_id );

sub gen_recon {
    my ( $client_id, $period_id, $atomic ) = @_;
    my $tempSettings = Common::NumericFormat::TemporarySettings( showThousandsFlag => 0 );

    my $reconReport = BookPub::Sale::Report::Reconciliation->new( clientID => $client_id, periodID => $period_id );
    my $xls_file_recon = $reconReport->filePath();

    if ( -e $xls_file_recon ) {
        Common::Log::Print("$xls_file_recon, removing it...");
        die "\nCan't remove $xls_file_recon : $!\n" unless ( unlink $xls_file_recon );
    }

    if ( !$reconReport->create() ) {
        Common::Log::Print("Error: Recon Report creation failed");
        return;
    }

    Common::Log::Print("Recon Report created: $xls_file_recon") if ( -e $xls_file_recon );
}

sub usage {
    my $err = shift;

    print "$err\n\n" if ($err);

    print <<EOF;
usage: $0 [-re] -c CLIENT_ID -p PERIOD_ID

-r           : runs only the royalty report
-e           : runs only the reconciliation report
-c CLIENT_ID : is the client ID
-p PERIOD_ID : is the period ID
EOF

    exit;
}

