#!/usr/bin/perl -w

use strict;

UncrossedSubtotals->start();

package UncrossedSubtotals;

use Data::Dumper;

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

use RPS::DB::Item::ArtistRoyaltyRun;
use RPS::DB::Item::ArtistRoyaltyStatement;
use RPS::DB::Item::ArtistRoyaltyAlbum;
use RPS::DB::Item::Publisher;

use base 'Common::Script';

sub _options {
    {
        client_id => {
            short       => 'c',
            description => 'Limit to client id',
            required    => 0,
            parameter   => 'i'
        },
        exec_mode => {
            short       => 'e',
            description => 'commit changes',
            required    => 0,
        },
    };
}

# 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 run_process {
    my $self = shift;
    $self->SUPER::run_process();
}

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

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

    my $execMode = $self->param('exec_mode');

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

    # MBS: I'm commenting out the 'ADD COLUMN' below because it's handled separately through the DB Diff tool
    #
    # Add the new column
    #
    #my $sql = "ALTER TABLE `artist_royalty_statement` ADD COLUMN `uncrossed_subtotal` DECIMAL(16,4) NOT NULL DEFAULT 0.0000";
    #if ( $execMode )
    #{
    #   my $sth = $dbo->DoCmd($sql);
    #}

    #
    # Now update the statements
    #
    my $sql =
        "UPDATE artist_royalty_statement rs "
      . "SET rs.uncrossed_subtotal = "
      . "  (SELECT SUM(total) FROM artist_royalty_album ra "
      . "   WHERE ra.artist_royalty_statement_id = rs.artist_royalty_statement_id "
      . "AND ra.is_cross_collateralized = 0)";

    if ($execMode) {
        my $sth = $dbo->DoCmd($sql);
        Log->notice( "Processed artist statements for client " . $client->ClientName() );
    }

    Log->notice("------------------------------------------------------------");
    Log->notice(" ");

}

1;
