#!/usr/bin/perl

use strict;
use Getopt::Std;

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

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

$| = 1;

# Parse the command-line.
#
my ($clientID, $inputFile) =  parseCommandLine();

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

open(F, $inputFile) or die "oops: $!\n";
while (<F>)
{
    chop;
    my ($acctID, undef, $balance) = split /\t/;
    next if ($balance == 0);
    $acctID =~ s/[^\d-]+//g;
    #$name =~ s/"//g;

    my $coll = RPS::DB::Item::ArtistPayee->Match($acctID);
    unless ($coll->hasNext())
    {
        print "no match: $_\n";
        next;
    }

    if ($coll->size() > 1)
    {
        print "multi-match: $_\n";
        next;
    }

    my $match = $coll->next();
    $match->opening_balance($balance);
    $match->save();
}

# -------------------------------------------------------------
# Subroutines
# -------------------------------------------------------------


sub parseCommandLine
{
    my %opt;
    getopts('c:f:M:', \%opt);

    my $inputFile = $opt{f};
    my $clientID = $opt{c};

    unless ($clientID =~ /^\d+$/ && $clientID > 0)
    {
	    die usage("You must specify a valid client ID");
    }

    unless ($inputFile)
    {
	    die usage("You must specify a catalog file to import");
    }

    unless (-e $inputFile)
    {
	    die usage("The specified catalog file does not exist");
    }

    return ($clientID, $inputFile);
}


sub usage
{
	my $errstr = shift;
	my $text = ($errstr) ? "ERROR: $errstr\n" : '';
	$text .= "Usage: $0 -c <clientID> -f <inputFile>\n";
	return $text;
}
