#---------------------------------------------------------------
# ____                   _ _         ____  _
#|  _ \ ___  _   _  __ _| | |_ _   _/ ___|| |__   __ _ _ __ ___
#| |_) / _ \| | | |/ _` | | __| | | \___ \| '_ \ / _` | '__/ _ \
#|  _ < (_) | |_| | (_| | | |_| |_| |___) | | | | (_| | | |  __/
#|_| \_\___/ \__, |\__,_|_|\__|\__, |____/|_| |_|\__,_|_|  \___|
#            |___/             |___/
#
# Copyright (C) 2013 RoyaltyShare, Inc.   All Rights Reserved
#---------------------------------------------------------------

package RPS::LabelRoyalty::Fast::Static::LabelPayeeAccounts;

use strict;
use Data::Dumper;
use File::Path;

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

use Data::Dumper;
use DB_File;

use Common::Log;

use base 'RPS::LabelRoyalty::Fast::Static';

use constant kMinPayment => 0;
use constant kBalance    => 1;
use constant kOnHold     => 2;

sub FileName            { 'label_payee_accounts' }
sub CacheQueryTableList { "'finance_transaction','label_payee_account','label_payee'" }

sub _Create {
    my ( $class, $filename, $payorID ) = @_;

    # !!! Ok, so I need to fetch the last transaction

    my %hash;
    $DB_BTREE->{'flags'} = R_DUP;
    tie %hash, "DB_File", $filename, O_RDWR | O_CREAT, 0666, $DB_HASH or die "Error opening $filename: $!\n";

    # This configures Dumper to use a format that can be eval'd directly into a variable.
    # Otherwise it lards it up with additional notation.
    #
    $Data::Dumper::Terse = 1;

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

    my %tempHash;
    my $sth;

    my $labelAccountSQL = qq/
    SELECT 
    label_payee_account.label_payee_id,
    label_payee_account.min_payment,
    label_payee_account.finance_account_id,
    label_payee.status
    FROM label_payee_account
    JOIN label_payee ON (label_payee_account.label_payee_id = label_payee.label_payee_id)
    WHERE label_payee_account.payor_id=$payorID
    AND label_payee.status in (1,2)
    /;
    $sth = $dbo->DoCmd($labelAccountSQL);

    while ( my @array = $sth->fetchrow_array() ) {
        my $accountID = $array[2];
        my $balance = _accountBalance( $accountID, $dbo );

        $tempHash{ $array[0] }{min_payment} = $array[1];
        $tempHash{ $array[0] }{balance}     = $balance;
        $tempHash{ $array[0] }{on_hold}     = 2 == $array[3] ? 1 : 0;
    }

    my $labelContractSQL = qq/
    SELECT 
    distinct(label_contract.label_payee_id),
    label_payee.status
    FROM label_contract 
    JOIN label_payee USING (label_payee_id)
    WHERE label_contract.payor_id=$payorID
    AND label_payee.status in (1,2)
    /;
    $sth = $dbo->DoCmd($labelContractSQL);

    while ( my @array = $sth->fetchrow_array() ) {

        # This essentially just puts a blank record in the hash.
        # Well, except that we'll know the payee's status.
        #
        $tempHash{ $array[0] }{on_hold} = 2 == $array[1] ? 1 : 0;
    }

    # Now output the data
    #
    while ( my ( $key, $value ) = each %tempHash ) {
        my $balance    = $value->{balance}     ? $value->{balance}     : 0;
        my $minPayment = $value->{min_payment} ? $value->{min_payment} : 0;
        my $onHold     = $value->{on_hold};

        $hash{$key} = "$minPayment\t$balance\t$onHold";
    }

    untie %hash;
}

sub _accountBalance {
    my ( $accountID, $dbo ) = @_;
    my $balanceSql =
"select balance from finance_transaction where finance_transaction_id = (select MAX(finance_transaction_id) from finance_transaction where finance_account_id=$accountID)";

    my $innerSTH = $dbo->DoCmd($balanceSql);
    my $bArray   = $innerSTH->fetchrow_arrayref();
    my $balance  = $bArray->[0];
    Log->info("balance for account $accountID: $balance");

    return $balance;
}

sub GetLabelPayeeAccounts {
    my ( $class, $dataPath ) = @_;

    my $filename = "$dataPath/" . $class->FileName();

    my %hash;
    my $dbObj = tie %hash, "DB_File", $filename, O_RDONLY, 0666, $DB_HASH or die "Error opening $filename: $!\n";

    return \%hash;
}

1;

