#!/usr/bin/perl -w

use strict;

Consolidate->start();

package Consolidate;

use lib '/app/tools/common/lib';
use lib '/app/tools/rps/lib';
use Common::RSApp;
use Common::Client;
use RPS::DB::Item::ArtistRoyaltyRunMissedSaleLog;
use RPS::DB::Item::ConsolidatedArtistRoyaltyRunMissedSaleLog;
use RPS::DB::Item::ArtistRoyaltyRun;
use RPS::RoyaltyRun::Status;
use RPS::DB::Item::ProductType;
use RPS::DB::Item::Product;
use RPS::DB::Item::Album;
use RPS::DB::Item::Track;
use RPS::DB::Item::Artist;
use RPS::DB::Item::NewArtistContract;

use base 'Common::Script';

sub _options {
    {
        client_id => {
            short       => 'c',
            description => 'Limit to client id',
            required    => 0,
            parameter   => 'i'
        },
        run_id => {
            short       => 'r',
            description => 'Limit to run id',
            required    => 0,
            parameter   => 'i'
        },
    };
}

# Override to only run on RPS clients.
#
sub _getProductionClientIDs {
    #
    # No reason to limit this to the 'local' clients...
    #
    return Common::RSDB::GetAllRPSClientIDs();
}

sub _getLocalClientIDs {
    return Common::RSDB::GetLocalRPSClientIDs();
}

sub _process {
    my ($self) = @_;

    my $client = Common::Client::Current();
    my $dbo    = Common::RSApp::GetClientDB();

    Log->notice("------------------------------------------------------------");
    Log->notice( "Starting " . $client->ClientName() );

    # If we were not given a specific run id, fetch all run ids.
    #
    my @runIDs;
    if ( $self->{_run_id} ) {
        push @runIDs, $self->{_run_id};
    } else {

        # Don't rely on the run table.  There may be orphaned data lurking in the log table.
        # So use the distinct ids from there.
        #
        my $sth = $dbo->DoCmd("SELECT DISTINCT(artist_royalty_run_id) AS artist_royalty_run_id FROM artist_royalty_run_missed_sale_log");
        while ( my $hr = $sth->fetchrow_hashref() ) {
            push @runIDs, $hr->{artist_royalty_run_id};
        }
    }

    foreach my $runID (@runIDs) {

        # If we've already consolidated this run, don't do it again...
        #
        my $sth =
          $dbo->DoCmd("SELECT COUNT(*) as count FROM consolidated_artist_royalty_run_missed_sale_log WHERE artist_royalty_run_id=$runID");
        my $hr = $sth->fetchrow_hashref();
        if ( 0 == $hr->{count} ) {
            $self->_processRunID($runID);
        }
    }

    # Re-optimize the table now, since we're all done.
    #
    Log->notice("Optimizing main table");
    $dbo->DoCmd("OPTIMIZE TABLE artist_royalty_run_missed_sale_log");
    Log->notice("------------------------------------------------------------");
    Log->notice(" ");

}

sub _processRunID {
    my ( $self, $runID ) = @_;

    Log->notice("Processing run $runID");

    # Get the run state.  Only consolidate 'good' runs'.
    #
    my $runStatus = 0;
    my $run = RPS::DB::Item::ArtistRoyaltyRun->Lookup( artist_royalty_run_id => $runID );
    if ($run) {
        $runStatus = $run->status();
        Log->notice( "  status:" . RPS::RoyaltyRun::Status::StatusString($runStatus) );

        if (   RPS::RoyaltyRun::Status::kComplete == $runStatus
            || RPS::RoyaltyRun::Status::kCommitted == $runStatus
            || RPS::RoyaltyRun::Status::kInvalidated == $runStatus
            || RPS::RoyaltyRun::Status::kClosed == $runStatus ) {
            Log->notice("  consolidating...");
            RPS::DB::Item::ConsolidatedArtistRoyaltyRunMissedSaleLog->BuildForRun($runID);
        }
    } else {
        Log->notice("  run not found in artist_royalty_run table");
    }

    # If the status is anything but complete or committed, purge it from the old table.
    # !!! Well, don't mess with runs that are still in progress!
    #
    if (   RPS::RoyaltyRun::Status::kComplete != $runStatus
        && RPS::RoyaltyRun::Status::kCommitted != $runStatus
        && RPS::RoyaltyRun::Status::kInvalidated != $runStatus
        && RPS::RoyaltyRun::Status::kRunning != $runStatus ) {
        Log->notice("  deleting from main table");
        RPS::DB::Item::ArtistRoyaltyRunMissedSaleLog->DeleteByRunID($runID);
    }
}

