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

package RPS::LabelRoyalty::Fast::Script::MapPendingTransactions;

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::LabelRoyalty::Fast::Static::LabelPayeePendingTransactions;
use RPS::LabelRoyalty::Fast::Mapped::Data;


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'
    },
    #
    # For now we'll assume the sales data is in there as well.
    # Some day that may not be the case...

    index_range =>
    {
        short       => 'i',
        required    => 0,
        description => 'First,Last data indexes to process.  Ex: -s0,10000',
        parameter   => 's',
    },
}}



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

    my ($firstIndex, $lastIndex) = $self->_parseFirstLastIndex($self->param('index_range'));

    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 Transactions");
    my $transactions = RPS::LabelRoyalty::Fast::Static::LabelPayeePendingTransactions->GetLabelPayeePendingTransactions($dataPath, $firstIndex, $lastIndex);



    # This is the main output stream.
    # !!! We will possibly need more for error or missed sale logging...
    #
    my $incomeItemFD = $self->_openIncomeItemFileDescriptor($outputDirectory);
    

    Log->info("Processing transactions...");
    foreach my $line (@$transactions)
    {
        Log->info("\n\nTRANSACTION LINE:", $line);

        my @array = split("\t", $line);
        my $transaction = \@array;


        # Glean all the necessary identifiers out of the reserve record.
        # I don't think I should need to look at any other data...
        #
        # These are the records I need to map the reserve to the correct income item:
        #
        $self->_outputLine($incomeItemFD, $transaction);
    }
}


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

    open OUTPUT, "> $outputDirectory/" . RPS::LabelRoyalty::Fast::Mapped::Data->FileName() . "_$$.unsorted" or die "ERROR: $!";

    return *OUTPUT;
}

sub _parseFirstLastIndex
{
    my ($self, $rangeString) = @_;
    return unless $rangeString;

    my @bits = split(',', $rangeString);
    if (2 != scalar @bits || ($bits[1] <= $bits[0]))
    {
        $self->usage('ERROR: sale_range is invalid.');
    }
    return ($bits[0], $bits[1]);
}



sub _outputLine
{
    my ($self, $outFD, $transaction) = @_;

    Log->info("outputLine: ", $transaction);


    my $gFormatString = 
       '%12d'  # label_id        
     . "\t". RPS::LabelRoyalty::Fast::Mapped::Data::kDataTransaction
     . "\t0"
     . "\t0"
     . "\t0"
     . "\t0"
     . "\t0"
     . "\t0"
     . "\t".'%12d'  # pending transaction id
     . "\t".'%20.08f'  # amount
     . "\t".'"%s"'  # memo
     . "\t".'"%s"'  # check number
     . "\t".'"%s"'  # type code.  this is 4 char type, we'll store as a quoted string
     . "\t".'%s'    # date.  This will be a mysql-style date string or undef.
     . "\n";

    print $outFD sprintf($gFormatString, 
     $transaction->[RPS::LabelRoyalty::Fast::Static::LabelPayeePendingTransactions::kLabelPayeeID()], 
     $transaction->[RPS::LabelRoyalty::Fast::Static::LabelPayeePendingTransactions::kPendingTransactionID()],
     $transaction->[RPS::LabelRoyalty::Fast::Static::LabelPayeePendingTransactions::kAmount()],
     $transaction->[RPS::LabelRoyalty::Fast::Static::LabelPayeePendingTransactions::kMemo()],
     $transaction->[RPS::LabelRoyalty::Fast::Static::LabelPayeePendingTransactions::kCheckNumber()], 
     $transaction->[RPS::LabelRoyalty::Fast::Static::LabelPayeePendingTransactions::kTypeCode()], 
     $transaction->[RPS::LabelRoyalty::Fast::Static::LabelPayeePendingTransactions::kDate()], 
     );
     
}


1;
