#!/usr/bin/perl -w

use strict;
use Getopt::Std;
use File::Basename;

use lib '/app/tools/common/lib';
use Common::RSApp;

use lib '/app/tools/rps/lib';
use RPS::RoyaltyRun::RoyaltyRunStatusList;

MAIN: {
    my %opts = parseCommandLine();

    Common::Log::Debug("Starting Royalty Run Status Check");

    my $appSingleton = new Common::RSApp( clientID => $opts{clientID} );
    my $rrList = RPS::RoyaltyRun::RoyaltyRunStatusList->new( payorID => $opts{payorID}, usMechanical => 1 );

    print Common::WriteXML::GetXMLString( $rrList, undef, skip_array_indexing => 1 );

    print "\nValid: ";
    print $rrList->validate() ? "yes\n" : "no\n";
}

sub parseCommandLine {
    my %opt;
    my %config;
    my $infile;

    getopts( 'p:c:d', \%opt ) || usage();

    #
    # Check for options and validate them
    #

    # Client ID
    usage("ClientID Required") unless ( $opt{c} );
    usage("ClientID must be numeric") unless ( $opt{c} =~ /^\d+$/ );

    $config{clientID} = $opt{c};

    # Payor ID
    usage("PlientID must be numeric") if ( defined( $opt{p} ) && $opt{p} !~ /^\d+$/ );
    $config{payorID} = $opt{p};

    $ENV{CLIENT_ID} = $ENV{DEBUG} = $config{clientID};
    $ENV{DEBUG} = 0 unless ( $opt{d} );

    return %config;
}

sub usage {
    my $errstr = shift;
    printf STDERR "%s%s",
      $errstr ? "ERROR: $errstr\n" : "",
      "USAGE: "
      . basename($0)
      . " -c <clientID> [-d]\n"
      . "   -c - Client ID (required)\n"
      . "   -p - Payor ID\n"
      . "   -d - enable debugging\n";

    exit 1;
}
