#!/usr/bin/perl
use strict;

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

use lib '/app/tools/common/lib';
use Common::DB::Item;

#use lib '/app/tools/data_classes/lib';
#use File::Sale;
use lib '/app/tools/raptor/lib';
use Raptor::DB::Item::Sale;

use lib '/app/tools/rps/lib';
use RPS::DB::Item::ArtistContractTermReserve;
use RPS::DB::Item::Product;
use RPS::DB::Item::LicenseReserve;
use RPS::DB::Item::MechanicalCarryover;
use RPS::DB::Item::ProductPrice;
use RPS::DB::Item::ProductTrack;

my $gVerbosityLevel = 1;

# Parse the command-line options.
#
my %options;
_parseCommandLine( \%options );

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

# product_id is a key in the following tables:
# artist_contract_term_reserve
# bonus_track (we can skip this - we always query this with a product_id from another source)
# license_reserve
# mechanical_carryover
# mechanical_statement_item  (this is a derrivative table, don't look at this)
# product_price
# product_track (We can skip this - never do a 'get all')
# royalty_statement_item  (another derrivative table)
# sale

# So, first, create a hash of all the valid product_ids.
#
_report("building hash of product_ids");
my %productIDs;
my $allProducts = RPS::DB::Item::Product->GetAll();
while ( my $product = $allProducts->next() ) {
    $productIDs{ $product->product_id } = 1;
}

# !!! We'll use the same interface we use in run_mechanicals.
# !!! Really need to re-name this method...
_report("\n--- checking sale table");
_checkCollection( Raptor::DB::Item::Sale::GetDualtoneUnprocessedMechanicalSales() );

_report("\n--- checking license_reserve table");
_checkCollection( RPS::DB::Item::LicenseReserve->GetAll() );

_report("\n--- checking mechanical_carryover table");
_checkCollection( RPS::DB::Item::MechanicalCarryover->GetAll() );

_report("\n--- checking product_price table");
_checkCollection( RPS::DB::Item::ProductPrice->GetAll() );

sub _checkCollection {
    my ($collection) = @_;
    while ( my $thing = $collection->next() ) {
        if ( !$productIDs{ $thing->product_id } ) {
            _report( "BAD : " . Dumper($thing) );
        }
    }
}

sub _usage {
    print "\nusage: $0 -c client_id [-V]\n";
    print "\n";
    print "Arguments:\n";
    print "\t-c <client_id>\t\tThe client_id of the client to process\n";
    print "\t-V <N>\t\t\tVerbosity level - 0 means no output\n";
}

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

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

# Pass dates in 'yyyy-mm-dd' format.
#
sub _parseCommandLine {
    my ($settings) = @_;

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

    if ( !$opt{c} ) {
        _usage();
        exit(1);
    }
    $settings->{clientID} = $opt{c};

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

