#!/usr/bin/perl -w

use strict;

Calculate->start();

package Calculate;

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::MechanicalRun;
use RPS::DB::Item::MechanicalStatementPublisher;
use RPS::DB::Item::Publisher;

use base 'Common::Script';

sub _options {
    {
        client_id => {
            short       => 'c',
            description => 'Limit to client 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 run_process {
    my $self = shift;
    print("client\trun\tstmt\tpubID\tpubName\tprvBal\tsub\ttSub\tsTotal\tdue\tADJ\n");

    $self->SUPER::run_process();
}

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

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

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

    # So... need to find and fix on-hold stuff.
    # That should be swell.
    # Need to proceed in an orderly fashion, somehow.
    # Only want to look at runs from this year.
    # Need to follow all 'on-hold' publishers through each complete run.

    my %publishers;

    my $allRuns =
      RPS::DB::Item::MechanicalRun->GetAllLegacy("SELECT * FROM mechanical_run WHERE status in (1,2,5) ORDER BY mechanical_run_id asc");
    while ( my $run = $allRuns->next() ) {
        Log->info( " RUN: " . $run->mechanical_run_id );

        # Find the on-hold dudes for this run.
        #
        my $onHoldItems = RPS::DB::Item::MechanicalStatementPublisher->GetAll(
"SELECT * FROM mechanical_statement_publisher WHERE on_hold=1 AND mechanical_statement_id IN (select mechanical_statement_id from mechanical_statement where mechanical_run_id="
              . $run->mechanical_run_id()
              . ")" );
        while ( my $onHoldItem = $onHoldItems->next() ) {

            # For now, just stash this item.  We'll iterate over the lists later.
            # !!! Well, should we do that?   What if something goes on hold, then off hold, then back on again?
            # !!! Might need to adjust this logic to account for that.
            #
            push @{ $self->{_statementPublisherItems}{ $onHoldItem->publisher_id() } },
              { item => $onHoldItem, runID => $run->mechanical_run_id() };
            if ( !$publishers{ $onHoldItem->publisher_id() } ) {
                my $p = RPS::DB::Item::Publisher->Lookup( publisher_id => $onHoldItem->publisher_id() );
                my $name = $p->publisher_name;
                if ( $p->agent_id || $p->admin_id ) {
                    $name .= ' (*)';
                }
                $publishers{ $onHoldItem->publisher_id() } = $name;
            }
        }
    }

    # Now let's look at the items we've found
    #
    my $lastPubID = 0;
    my $adj       = 0;
    foreach my $publisherID ( sort { $a <=> $b } keys %{ $self->{_statementPublisherItems} } ) {
        if ( 0 != $lastPubID && $lastPubID != $publisherID ) {
            print( $client->ClientName() . "\t\t\t$lastPubID\t" . $publishers{$lastPubID} . "\t\t\t\t\t\t$adj\n" );
            $lastPubID = $publisherID;
            $adj       = 0;
        }
        $lastPubID = $publisherID;

        my $pubStatementItems = $self->{_statementPublisherItems}{$publisherID};
        foreach my $dataBlock (@$pubStatementItems) {
            my $item  = $dataBlock->{item};
            my $runID = $dataBlock->{runID};
            print(  $client->ClientName() . "\t"
                  . $runID . "\t"
                  . $item->mechanical_statement_id() . "\t"
                  . $item->publisher_id() . "\t"
                  . $publishers{$publisherID} . "\t"
                  . $item->previous_balance() . "\t"
                  . $item->subtotal() . "\t"
                  . $item->transaction_subtotal() . "\t"
                  . $item->statement_total() . "\t"
                  . $item->amount_due()
                  . "\n" );

            $adj += $item->statement_total() . "\n";
        }
    }
    if ($lastPubID) {
        print( $client->ClientName() . "\t\t\t$lastPubID\t" . $publishers{$lastPubID} . "\t\t\t\t\t\t$adj\n" );
    }

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

    $self->{_statementPublisherItems} = {};
}

1;
