#!/usr/bin/perl
#------------------------------------------------------------
# Copyright (C) 2006 RoyaltyShare, Inc.   All Rights Reserved
# $Id$
#------------------------------------------------------------
use strict;

use Data::Dumper;
use Getopt::Std;
use POSIX qw(ceil);
use Carp;

use lib '/app/tools/common/lib';
use Common::Assert;

use lib '/app/tools/rps/lib';
use RPS::Mechanical::MechanicalRun;
use RPS::DB::Item::MechanicalRun;
use RPS::DB::Item::Product;
use RPS::DB::Item::Publisher;
use RPS::DB::Item::PublisherAccount;
use RPS::DB::Item::Track;
use RPS::DB::Item::TrackLicense;
use RPS::DB::Item::LicenseReserve;
use RPS::DB::Item::LicenseReserveRun;
use RPS::DB::Item::ReserveLiquidation;
use RPS::DB::Item::PendingTransaction;
use RPS::DB::Item::MechanicalStatement;
use RPS::DB::Item::MechanicalStatementTransaction;
use RPS::DB::Item::MechanicalStatementItem;
use RPS::DB::Item::MechanicalCarryover;
use RPS::DB::Item::MechanicalRunCarryover;
use RPS::DB::Item::MechanicalStatementLicense;
use RPS::DB::Item::SaleMechanicalStatementItemMap;
use RPS::DB::Item::FinanceAccount;
use RPS::DB::Item::FinanceTransaction;

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

my $gVerbosityLevel = 1;
my $gRunLabel;

# Get the id from the command-line
#
my %options;
_parseCommandLine( \%options );
_rebuild( $options{clientID} );

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};
    }
}

sub _usage {
    print "\nusage: $0 -c <client_id> -r <mechanical_run_id>\n";
    print "\n";
    print "Arguments:\n";
    print "\t-c <client_id>\t\tThe client_id of the client to process\n";
    print "\t-r <mechanical_run_id>\t\tThe mechanical_run_id to commit\n";
}

sub _rebuild {
    my ($clientID) = @_;

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

    my $clientDB = Common::RSApp::GetClientDB();

    my $statementTransactions = RPS::DB::Item::MechanicalStatementTransaction->GetAll();
    while ( my $statementTrans = $statementTransactions->next() ) {
        my $statementItem =
          RPS::DB::Item::MechanicalStatement->Lookup( mechanical_statement_id => $statementTrans->mechanical_statement_id );
        next unless $statementItem;
        my $publisherID      = $statementItem->publisher_id;
        my $payorID          = $statementItem->payor_id;
        my $publisherAccount = RPS::DB::Item::PublisherAccount->Lookup( publisher_id => $publisherID, payor_id => $payorID );
        my $financeAccountID = $publisherAccount->finance_account_id;

        # Sanity check - should be exactly 1 finance transaction that will match.
        #
        my $where =
            "where finance_account_id=$financeAccountID"
          . " and amount="
          . $clientDB->DBQuote( $statementTrans->amount() )
          . " and type_code="
          . $clientDB->DBQuote( $statementTrans->type_code() );
        if ( defined $statementTrans->memo() ) {
            $where .= " and memo=" . $clientDB->DBQuote( $statementTrans->memo() );
        } else {
            $where .= " and memo is null";
        }
        if ( defined $statementTrans->check_number() ) {
            $where .= " and check_number=" . $clientDB->DBQuote( $statementTrans->check_number() );
        } else {
            $where .= " and check_number is null";
        }

        my $sql = "SELECT COUNT(*) FROM finance_transaction $where";

        my $sth   = $clientDB->DoCmd($sql);
        my $hr    = $sth->fetchrow_hashref();
        my $count = $hr->{'COUNT(*)'};
        die "ERROR: count is $count for finance account $financeAccountID statement trans: " . Dumper($statementTrans) if ( 1 != $count );

        # Create the new pending transaction.
        #
        my $newPending = RPS::DB::Item::PendingTransaction->Create(
            finance_account_id => $financeAccountID,
            amount             => $statementTrans->amount(),
            type_code          => $statementTrans->type_code(),
        );
        if ( defined $statementTrans->memo() ) {
            $newPending->memo( $statementTrans->memo() );
        }
        if ( defined $statementTrans->check_number() ) {
            $newPending->check_number( $statementTrans->check_number() );
        }
        $newPending->save();

        # Delete the finance_transaction.
        # (the old-fashioned way)
        #
        $clientDB->DoCmd("DELETE from finance_transaction $where");
    }
}

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

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

