#!/usr/bin/perl
use strict;


use Data::Dumper;
use Getopt::Std;
use POSIX qw(ceil);
use POSIX ":sys_wait_h";
use Sys::Hostname;
use Carp;


use lib '/app/tools/common/lib';
use Common::DB::Item;
use Common::Assert;
use Common::TextProgressBar;
use Common::Timer;
use Common::DB::Item::Service;

use lib '/app/tools/rps/lib';
use RPS::DB::Item::MechanicalRun;
use RPS::DB::Item::MechanicalStatement;

my $gVerbosityLevel = 1;



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


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

my $runs = RPS::DB::Item::MechanicalRun->GetAll();
while (my $run = $runs->next())
{
    _fixRun($run);
}


sub _fixRun
{
    my ($run) = @_;

    my $runID = $run->mechanical_run_id;
    _report("\n---- Converting run $runID");

    my @payors = RPS::DB::Item::MechanicalStatement->GetDistinctPayorsByRunID($runID);
    if (1 == scalar @payors)
    {
        _report("  just 1 payor : " . $payors[0]);

        $run->payor_id($payors[0]);
        $run->save();
    }
}



sub _usage
{
    print "\nusage: $0 -c client_id [-V]\n";
    print "\n";
    print "Arguments:\n";
    print "\t-c <client_id>\t\tThe client_id of the client to process\n";
    print "\t-V <N>\t\t\tVerbosity level - 0 means no output\n";
}


sub _report
{
    my ($string, $verbosity) = @_;
    $verbosity = 1 unless defined $verbosity;

    if ($gVerbosityLevel >= $verbosity)
    {
        print $string . "\n";
    }
}


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

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

    if (! $opt{c})
    {
        _usage();
        exit(1);
    }
    $settings->{clientID} = $opt{c};

    if (defined $opt{V})
    {
        $gVerbosityLevel = $opt{V};
    }
}
