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

package RPS::ArtistRoyalty::Fast::Static::Expenses;

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

use lib '/app/tools/common/lib';
use lib '/app/tools/rps/lib';

use Common::RSApp;
use Common::Log;
use DB_File;
use RPS::DB::Item::Expense;

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

# Note - oddly, the termRate value is always null in the ArtistRoyaltyExpenseItem.

use constant kExpenseID            => 0;
use constant kAmount               => 1;
use constant kPercent              => 2;
use constant kMemo                 => 3;
use constant kTrackID              => 4;
use constant kAlbumID              => 5;
use constant kArtistContractID     => 6;
use constant kArtistPayeeID        => 7;
use constant kArtistContractTermID => 8;
use constant kDefaultTermRate      => 9;
use constant kName                 => 10;
use constant kPreProcess           => 11;
use constant kCrossed              => 12;

#
# If the expense is 'pre-process', we actually just want to provide
# the term id.  If there isn't a term id, it isn't 'pre-process'.
# That just seems to be used to group stuff together,.
# Might as well join to the contracts, take care of all of that now.
#

# I may need the term's default rate.

sub FileName { 'expenses' }

sub CacheQueryTableList {
    "'expense','track_contract','track','new_artist_contract','new_artist_contract_term','expense_name','artist_payee','expense_type'";
}

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

    my $albumContractType = RPS::DB::Item::Expense::kParentAlbumContract;
    my $trackContractType = RPS::DB::Item::Expense::kParentTrackContract;

    open EXPENSEFILE, "> $filename" or die "ERROR: Unable to open $filename for writing: $!";

    # We're basically going to union at least two queries together.
    # Some of these link to track contracts, and some to album contract, so it's
    # ultimately faster and easier to use a union.

    my $trackSql = qq/
    SELECT
    expense.expense_id,
    expense.amount,
    expense.percent,
    expense.memo,
    track_contract.track_id,
    track.album_id,
    track_contract.artist_contract_id,
    new_artist_contract.artist_payee_id,
    IF(expense.pre_process = 1, new_artist_contract_term.artist_contract_term_id, 0),
    IF(expense.pre_process = 1, new_artist_contract_term.rate, 0),
    expense_name.name,
    expense.pre_process,
    track_contract.cross_collateralized
    FROM expense
    JOIN track_contract ON (track_contract.track_contract_id = expense.parent_id)
    JOIN track USING (track_id)
    JOIN new_artist_contract USING (artist_contract_id)
    JOIN artist_payee ON (new_artist_contract.artist_payee_id = artist_payee.artist_payee_id)
    JOIN expense_type USING (expense_type_id)
    JOIN expense_name USING (expense_name_id)
    LEFT JOIN new_artist_contract_term ON (new_artist_contract_term.priority=0 AND new_artist_contract_term.artist_contract_id=new_artist_contract.artist_contract_id)
    WHERE new_artist_contract.payor_id=$payorID
    AND expense.processed=0
    AND expense.parent_type=$trackContractType
    AND track_contract.status=1
    AND artist_payee.status in (1,2)
    AND new_artist_contract.deleted = 0
    /;

    my $albumSql = qq/
    SELECT
    expense.expense_id,
    expense.amount,
    expense.percent,
    expense.memo,
    0,
    album_contract.album_id,
    album_contract.artist_contract_id,
    new_artist_contract.artist_payee_id,
    IF(expense.pre_process, new_artist_contract_term.artist_contract_term_id, 0),
    IF(expense.pre_process, new_artist_contract_term.rate, 0),
    expense_name.name,
    expense.pre_process,
    album_contract.cross_collateralized
    FROM expense
    JOIN album_contract ON (album_contract.album_contract_id=expense.parent_id)
    JOIN new_artist_contract USING (artist_contract_id)
    JOIN artist_payee ON (new_artist_contract.artist_payee_id = artist_payee.artist_payee_id)
    JOIN expense_type USING (expense_type_id)
    JOIN expense_name USING (expense_name_id)
    LEFT JOIN new_artist_contract_term ON (new_artist_contract_term.priority=0 AND new_artist_contract_term.artist_contract_id=new_artist_contract.artist_contract_id)
    WHERE new_artist_contract.payor_id=$payorID
    AND expense.processed=0
    AND expense.parent_type=$albumContractType
    AND album_contract.status=1
    AND artist_payee.status in (1,2)
    /;

    my $sql = "$trackSql UNION $albumSql";

    my $dbo = Common::RSApp::GetClientDB();
    my $sth = $dbo->DoCmd($sql);
    while ( my $ar = $sth->fetchrow_arrayref() ) {

        # I've got text fields, so I may need a different delimiter than tab.
        # I guess I'll need to quote the field in the MappedItems file?
        # Or we go to an 'official' csv representation.
        # I'll try it with quotes first, we'll see what happens.
        #
        # Let's just escape everything.
        #
        my $escapedArray = $class->EscapeArray($ar);

        print EXPENSEFILE join( "\t", @$escapedArray ) . "\n";
    }

    close EXPENSEFILE;
}

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

    # Currently the sales file is a text file.
    # We'll use DB_RECNO, which allows us to access the file through
    # a tied array ref.
    #
    # !!! Or, we'll just return a file handle...   Don't really need fancy tied arrays for this, do we?
    #
    my $filename = "$dataPath/" . $class->FileName();

    my @array;
    tie @array, "DB_File", $filename, O_RDONLY, 0666, $DB_RECNO or die "Error opening $filename: $!\n";

    return \@array;
}

1;
