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

package RPS::ArtistRoyalty::Fast::Script::MapAlbumContractAccounts;

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

use Common::Util;
use Common::Log;
use Common::Parser;
use Common::WriteXML;

use RPS::ArtistRoyalty::Fast::Static::ArtistAlbumContractAccountBalances;
use RPS::ArtistRoyalty::Fast::Static::CrossedAlbumContracts;
use RPS::ArtistRoyalty::Fast::Mapped::Data;

# The point of this mapper is to make sure we consider artist_contract/album pairs that
# have no sale activity but do have a previous balance.
# We should be able to emit a line that just contains the payee,contract_id, and album_id and
# the rest of the work will take care of itself.
# (Use the '0' data type, since we're not actually accumulating anything).

use base 'Common::Script';

sub _options {
    {
        client_id => {
            short       => 'c',
            required    => 1,
            description => 'Limit to this client id',
            parameter   => 'i'
        },
        data_path => {
            short       => 'd',
            required    => 1,
            description => 'path to directory containing static data',
            parameter   => 's'
        },
        output_path => {
            short       => 'o',
            required    => 1,
            description => 'path to directory to write output files',
            parameter   => 's'
        },
    };
}

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

    my $dataPath = $self->param('data_path');

    my $outputDirectory = $self->param('output_path');

    # JPK - Should it be the responsibility of this process to create the directory if
    # it doesn't already exist?   It's a bit of a stretch, but then again it's convenient...
    #
    if ( !-d $outputDirectory ) {

        # !!! Might want to make this behavior optional...
        #
        mkpath($outputDirectory);
    }

    Log->info("Getting Balance Data");
    my $balances = RPS::ArtistRoyalty::Fast::Static::ArtistAlbumContractAccountBalances->GetAccountBalances($dataPath);
    my $crossed  = RPS::ArtistRoyalty::Fast::Static::CrossedAlbumContracts->GetCrossedAlbumContracts($dataPath);

    my $incomeItemFD = $self->_openIncomeItemFileDescriptor($outputDirectory);

    foreach my $artistPayeeID ( keys %$balances ) {
        Log->info(" looking at artist payee id $artistPayeeID");
        my $hashRef = eval( $balances->{$artistPayeeID} );
        foreach my $albumID ( keys %$hashRef ) {
            Log->info(" looking at album id $albumID");
            foreach my $artistContractID ( keys %{ $hashRef->{$albumID} } ) {
                Log->info(" looking at artist contract id $artistContractID");
                if ( $hashRef->{$albumID}{$artistContractID} != 0 ) {
                    my $crossedFlag = $crossed->{$albumID}{$artistContractID};
                    Log->info(" writing line");
                    $self->_outputLine( $incomeItemFD, $artistPayeeID, $albumID, $artistContractID, $crossedFlag );
                }
            }
        }
    }
}

sub _openIncomeItemFileDescriptor {
    my ( $self, $outputDirectory ) = @_;

    my $fullPath = "$outputDirectory/" . RPS::ArtistRoyalty::Fast::Mapped::Data->FileName() . "_$$.unsorted";
    Log->info(" OUTFILE: $fullPath");
    open OUTPUT, "> $fullPath" or die "ERROR: $!";

    return *OUTPUT;
}

sub _outputLine {
    my ( $self, $outFD, $artistPayeeID, $albumID, $artistContractID, $crossedFlag ) = @_;

    $crossedFlag = 0 unless $crossedFlag;

    my $gFormatString = '%12d'    # payee_id
      . "\t" . '%12d'             # album_id
      . "\t" . '%12d'             # artist_contract_id
      . "\t" . RPS::ArtistRoyalty::Fast::Mapped::Data::kTypeAccount . "\t" . '0' . "\t" . '0' . "\t" . '%d' . "\n";

    print $outFD sprintf( $gFormatString, $artistPayeeID, $albumID, $artistContractID, $crossedFlag, );
}

1;
