#!/usr/bin/perl

use strict;
use Getopt::Std;

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

use lib '/app/tools/rps/lib';
use RPS::Report::Command::MissingLicenseAccrual;
use RPS::DB::Item::MechanicalRun;
use RPS::DB::Item::MechanicalRunUnlicensedTrackLog;

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

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

#my $commandObj = RPS::Report::Command::MissingLicenseAccrual->new(run_id => 73, download => 1);

# So, we're not going to use the Report object.  It's simply too massive to dea with unpaginated.
# Instead, we're simply going to iterate through the data and output the results line-by-line.
#
my $run = RPS::DB::Item::MechanicalRun->Lookup( mechanical_run_id => $runID );
my $reportingPeriod = Common::Client::Current()->Locale()->formatDate( $run->start_date ) . ' - '
  . Common::Client::Current()->Locale()->formatDate( $run->end_date );

# Print out the report header
#
print "Reporting Period\tLabel\tAlbum Title\tCatalog #\tUPC\tArtist\tTrack Title\tISRC\tShare\tConfig\tCumulative Accrual\n";

my $logLines = RPS::DB::Item::MechanicalRunUnlicensedTrackLog->GetByRunID($runID);
while ( my $logLine = $logLines->next() ) {
    my @line;
    push @line, $reportingPeriod;
    push @line, $logLine->label_name;
    push @line, $logLine->album_title;
    push @line, $logLine->catalog_number;
    push @line, $logLine->upc_ean;
    push @line, $logLine->track_artist_name;
    push @line, $logLine->track_title;
    push @line, $logLine->isrc;
    push @line, Common::Client::Current()->Locale()->formatNumber( $logLine->unlicensed_share, .2 ) . '%';
    push @line, $logLine->product_type;
    push @line, Common::Client::Current()->Locale()->formatNumber( $logLine->accrual, .2 );

    print join( "\t", @line ) . "\n";
}

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

    my $clientID = $opt{c};
    my $runID    = $opt{r};

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

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

    return ( $clientID, $runID );
}

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

