#!/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::RSDB;
use Common::RSApp;

use lib '/app/tools/rps/lib';
use RPS::DB::Item::NewArtistContract;
use RPS::DB::Item::NewArtistContractTerm;
use RPS::DB::Item::IncomeSource;


my $gVerbosityLevel = 1;


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



# Get a list of client IDS that are on this machine...
#
my @clientIDs;
if ($options{clientID})
{
    push @clientIDs, $options{clientID};
}
else
{
    @clientIDs = _getLocalClientIDs();
}

foreach my $clientID (@clientIDs)
{
    my $appSingleton = Common::RSApp->new(clientID => $clientID);

    _report("--- processing client $clientID", 2);
    
    # Loop through all contracts, looking for terms that have an income source
    # of 'stream'.  We'll clone that term, using 'VPD' instead.
    # If there aren't any, then presumably the default net revenue term will suffice.
    #
    my $allContracts = RPS::DB::Item::NewArtistContract->GetAll();
    while (my $contract = $allContracts->next())
    {
        # We can create the new terms on the fly, as we run through the collection.
        #
        my $allTerms = RPS::DB::Item::NewArtistContractTerm->GetByArtistContractID($contract->artist_contract_id);
        my $nextTermPriority = $allTerms->size();

        while (my $term = $allTerms->next())
        {
            if (RPS::DB::Item::IncomeSource::kIncomeSourceDigitalStream	== $term->income_source_id)
            {
                my $newTerm = RPS::DB::Item::NewArtistContractTerm->Copy(dbItem => $term);
                $newTerm->priority($nextTermPriority++);
                $newTerm->income_source_id(RPS::DB::Item::IncomeSource::kIncomeSourceVPD);
                $newTerm->save();

                _report("created term " . $newTerm->artist_contract_term_id . " in contract " . $contract->artist_contract_id, 2);
            }
        }

    }
}


sub _getLocalClientIDs
{
    # We have a nifty little script that will give us a list of client databases.
    #
    my $clientListString = `/app/tools/rps/bin/db/list_client_dbs.pl`;
    chomp $clientListString;


    # Find the client id that matches each database.
    #
    my @ids;
    my @dbNames = split(/ /, $clientListString);
    foreach my $dbName (@dbNames)
    {
        my $id = Common::RSDB::DBNameToClientID($dbName);
        push @ids, $id;

    }

    return @ids;
}

sub _usage
{
    print "\nusage: $0 [-c client_id] [-V verbosity]\n";
    print "\n";
    print "Arguments:\n";
    print "\t-c <client_id>\t\tThe client_id of the client to process - omit to process all clients\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";
    }
}

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

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

    # client id is optional - if omitted, we'll assume all clients.
    #
    if (defined $opt{c})
    {
        $settings->{clientID} = $opt{c};
    }

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