#!/usr/bin/perl
#------------------------------------------------------------ 
# Copyright (C) 2006 RoyaltyShare, Inc.   All Rights Reserved
# $Id$
#------------------------------------------------------------ 
use strict;
#use warnings;

use File::Path;
use Data::Dumper;
use Getopt::Std;
use Carp;

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

use lib '/app/tools/rps/lib';
use RPS::Statement::Artist::PDF;
use RPS::Statement::Mechanical::PDF;
use RPS::DB::Item::ArtistRoyaltyRun;
use RPS::DB::Item::MechanicalRun;
use RPS::DB::Item::ArtistRoyaltyStatement;
use RPS::DB::Item::MechanicalStatement;
use RPS::DB::Item::Region;
use RPS::DB::Item::RegionCountryMap;

$SIG{__DIE__} = \&Carp::confess;


use constant kCreateStatementScript => 'nice /app/tools/rps/bin/statements/createArtistStatementPDF.pl';

# This determines how much output we spew forth to STDERR.
# The user can set this with the -V command-line argument.
#
my $gVerbosityLevel = 1;

# Parse the command-line, then create the PDF!
#
my %options;
parseCommandLine(\%options);

my @clientIDs;
if ($options{clientID})
{
    push @clientIDs, $options{clientID};
}
else
{
    push @clientIDs, _getLocalClientIDs();
}

foreach my $clientID (@clientIDs)
{
    next if (23 == $clientID);  # skipping Compass

    my $appSingleton = Common::RSApp->new(clientID => $clientID);
    report("\n----------\nprocessing client $clientID : " . Common::RSDB::ClientIDToDBName($clientID));
    eval {
    my $usRegionID = createUSRegion($clientID);
    setLicensesToUS($clientID, $usRegionID);
    };
    if ($@)
    {
        report("Caught this exception: $@");
    }
}


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

sub setLicensesToUS
{
    my ($clientID, $usRegionID) = @_;

    my $dbo = Common::RSApp::GetClientDB();
    my $sql = "UPDATE track_license set region_id=$usRegionID";
    my $sth = $dbo->DoCmd($sql);
}


sub createUSRegion
{
    my ($clientID) = @_;

    # First, do they already have a 'United States' region?
    # Presumably, this will be the region that contains just 1 country: 'US'
    #
    my $matchedRegion;
    my $dbo = Common::RSApp::GetClientDB();
    my $sql = "select region_id,COUNT(*) from region_country_map where region_id in (select distinct region_id from region_country_map where country_code='US') group by region_id";
    my $sth = $dbo->DoCmd($sql);
    while (my $hr = $sth->fetchrow_hashref())
    {
        my $regionID = $hr->{'region_id'};

        # Is this region called 'US' or 'United States' or 'USA' ?
        #
        my $region = RPS::DB::Item::Region->Lookup(region_id => $regionID);
        if ('US' eq uc($region->name)
         || 'USA' eq uc($region->name)
         || 'United States' eq uc($region->name))
        {
            report(" !!! region $regionID _claims_ to be US, going to use that");
            $matchedRegion = $hr->{'region_id'};
            next;
        }
        # Should only be 1.
        #
        if ($hr->{'COUNT(*)'} == 1)
        {
            if ($matchedRegion)
            {
                report(" !!! had a matched region already, $matchedRegion");
            }
            else
            {
                $matchedRegion = $hr->{'region_id'};
            }
        }
    }

    if ($matchedRegion)
    {
        my $region = RPS::DB::Item::Region->Lookup(region_id => $matchedRegion);
        $region->is_default_mechanical_license_region(1);
        $region->save();
        report(" matched region $matchedRegion, region name " . $region->name . ", not creating new region");
        return $matchedRegion;
    }


    # Create a new US region.
    #
    my $newRegion = RPS::DB::Item::Region->Create
    (
        name => 'United Stated',
        is_default_mechanical_license_region => 1,
    );
    $newRegion->save();
    my $newRegionID = $newRegion->region_id;

    my $newMap = RPS::DB::Item::RegionCountryMap->Create
    (
        region_id => $newRegionID,
        country_code => 'US',
    );
    $newMap->save();
    return $newRegionID;
}







#
# Boring script stuff below...
#

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

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

    if (defined $opt{c})
    {
        $settings->{clientID} = $opt{c};
    }

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


sub usage
{
    print STDERR "\nusage: $0 -c <client_id> -r <artist_royalty_run_id> -p <output path>\n";
    print STDERR "\n";
    print STDERR "Arguments:\n";
    print STDERR "\t-c <client_id>\t\t\tThe client_id of the client to process\n";
    print STDERR "\t-r <artist_royalty_run_id>\tThe id of the artist royalty run\n";
    print STDERR "\t-p <output path>\t\tThe path to where we'll be saving these files\n";
}


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

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


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;
}


