#!/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::Master;
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 %seen = ();

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

    while ( $licenseColl->hasNext() ) {
        my $licenseObj = $licenseColl->next();
        next if ( $licenseObj->type == RPS::DB::Item::TrackLicense::kPublicDomain() );
        next if ( $seen{ $licenseObj->track_id } );

        my $track = RPS::DB::Item::Track->Lookup( track_id => $licenseObj->track_id );
        if ($track) {
            my $master = RPS::DB::Item::Master->Lookup( master_id => $track->master_id );
            if ( $master && !$master->duration ) {
                reportTrack( $track, $licenseObj );
                $seen{ $track->track_id } = 1;
            }
        }
    }
}

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

    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 $type;
    if ( $license->product_type_id == 2 ) {
        $type = "CD";
    } else {
        $type = "D";
    }

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

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

