#!/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 $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;
				}

				$totalShare += $licenseObj->share;

				if(!$licenseObj->date_issued)
				{
					reportLicense($licenseObj, $trackObj);
				}
			}

			if(!$publicDomain && $totalShare < 95)
			{
				reportTrack($trackObj, $totalShare);
			}
		}
		else
		{
			# report this track as having no licenses
			#
			reportTrack($trackObj);
		}

	}
}


sub reportLicense
{
	my ($license, $track) = @_;

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

	my $line = join("\t",
					$album->catalog_number,
					$album->title,
					$track->title,
					$publisher->publisher_name,
					$license->share,
					undef,
					$license->date_issued);

	reportLine($line);
}

sub reportTrack
{
	my ($track, $missingShare) = @_;
	$missingShare ||= 100;

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

	my $line = join("\t",
					$album->catalog_number,
					$album->title,
					$track->title,
					undef,
					undef,
					$missingShare,
					undef);

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


