#!/usr/bin/perl

# Copyright (C) 2006  RoyaltyShare, Inc.   All Rights Reserved
# $Id$

use strict;

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



# Use a global hash to hold application settings.
#
my %gSettings;


# Set default settings
#
_setDefaultSettings(\%gSettings);


# Parse the command-line options.
#
_parseCommandLine(\%gSettings);


# Instantiate the application singleton object.
#
my $appSingleton = Common::RSApp->new(clientID => $gSettings{clientID});


# We'll use STDOUT for output.
#
my $fh = \*STDOUT;


# Create the mechanical run object.
# (XXX) This will update the database.
# jpk - the point of the MechanicalRun object is to provide an abstraction around
# all the state (i.e. the data) of this run.  Rather than going to the database directly
# for the mechanical_statement-related stuff, we'll go through this class.
#
my $run = MechanicalRun->new
(
    clientID => $gSettings{clientID},
    startDate => $gSettings{startDate},
    endDate => $gSettings{endDate},
    dryRun => $gSettings{dryRun},       # pass 1 if you want to skip writing anything out to the db
    verbosity => $gSettings{verbosity},
    showProgress => $gSettings{showProgress},
    outputFileHandle => $fh,
);


# So... let's run some mechanicals!
#
$run->calculateMechanicals();

$run->commitToDB();

$run->writeCache();


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



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

    $settings->{verbosity} = 1;
    $settings->{showProgress} = 1;
}



# Pass dates in 'yyyy-mm-dd' format.
#
sub _parseCommandLine
{
    my ($settings) = @_;

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

    if (! $opt{s} || ! $opt{e} || ! $opt{c})
    {
        _usage();
        exit(1);
    }
    $settings->{startDate} = $opt{s};
    $settings->{endDate} = $opt{e};
    $settings->{clientID} = $opt{c};

    if (defined $opt{V})
    {
        $settings->{verbosity} = $opt{V};
    }
}


sub _usage
{
    print "\nusage: $0 -c client_id -s start_date -e end_date [-V n]\n";
    print "\n";
    print "Arguments:\n";
    print "\t-c <client_id>\t\tThe client_id of the client to process\n";
    print "\t-s <date>\t\tThe first day of the period to process, in YYYY-MM-DD format\n";
    print "\t-e <date>\t\tThe last day of the period to process, in YYYY-MM-DD format\n";
    print "\t-V <N>\t\t\tVerbosity level - 0 means no output\n";
}

