#!/usr/bin/perl

use strict;
use Getopt::Std;

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

use lib '/app/tools/rps/lib';
use RPS::DB::Item::Track;
use RPS::DB::Item::TrackLicense;
use RPS::DB::Item::Album;
use RPS::DB::Item::Publisher;

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

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

convertContracts();



#
# --- Subroutines
#

sub convertContracts
{

	# my %regionRates = (6 => 100, 7 => 85, 10 => 75, 0 => 50);

	# get collection of contracts
	#
	my $trackColl = RPS::DB::Item::Track->GetAll();

	while($trackColl->hasNext())
	{
		my $trackObj = $trackColl->next();
		next if($trackObj->mechanical_exempt);

		my $shareByType = {};

		my $licenseColl = RPS::DB::Item::TrackLicense->GetLicensesByTrackID($trackObj->track_id);
		if($licenseColl->hasNext())
		{
			my $totalShare = 0;
			my $publicDomain = 0;
			while($licenseColl->hasNext())
			{
				my $licenseObj = $licenseColl->next();
				if(RPS::DB::Item::TrackLicense::kPublicDomain() == $licenseObj->type)
				{
					$publicDomain = 1;
					next;
				}

				if($licenseObj->product_type_id)
				{
					$shareByType->{$licenseObj->product_type_id}->{total} += $licenseObj->share;

					if($licenseObj->inactive)
					{
						$shareByType->{$licenseObj->product_type_id}->{inactive} += $licenseObj->share;
					}
					else
					{
						$shareByType->{$licenseObj->product_type_id}->{active} += $licenseObj->share;
					}
				}
			}

			if(!$publicDomain)
			{
				foreach my $type (keys %$shareByType)
				{
					my $href = $shareByType->{$type};

					if($href->{total} > 101)
					{
						reportTrack($trackObj, $type, $href->{total}, $href->{active}, $href->{inactive});
					}
				}
			}
		}
	}
}


sub reportTrack
{
	my ($track, $type, $total, $active, $inactive) = @_;

	my $album = RPS::DB::Item::Album->Lookup(album_id => $track->album_id);

	my $typeLabel = $type;
	if($type == 2)
	{
		$typeLabel = "CD";
	}
	elsif($type == 3)
	{
		$typeLabel = "D";
	}

	my $line = join("\t",
					$album->catalog_number,
					$album->title,
					$track->track_number,
					$track->title,
					$typeLabel,
					$active,
					$inactive,
					$total);

	reportLine($line);
}


sub reportLine
{
	my $line = shift;

	print $line ."\n";
}

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

    my $clientID = $opt{c};

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

    return $clientID;
}


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


