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

package RPS::ArtistRoyalty::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::ArtistRoyalty::Fast::Static::ArtistPayeePendingTransactions;
use RPS::ArtistRoyalty::Fast::Mapped::Data;

use RPS::ArtistRoyalty::Fast::TermType;

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::ArtistRoyalty::Fast::Static::ArtistPayeePendingTransactions->GetArtistPayeePendingTransactions( $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::ArtistRoyalty::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 );

    # So, these guys 'hash' to the statement.  They are not associated with
    # an album id in any way.
    # I'm wondering where they should land, then, after sorting:  Before everything else, or after?
    # It may not really matter, as long as they don't end up in the _middle_ of albums and income items.
    # Which they really shouldn't, since the album_id will be 0.

    # Now that we're sorting 'numerically', I don't think I need to preserve _ANY_ of the columns other than payee_id.
    # We'll see how that works out.

    # Almost works, except that we end up with a bogus, empty album.
    # We might be able to get away with setting up the Album output routine to do nothing
    # if there isn't an album id.

    my $gFormatString = '%12d'                                                             # payee_id
      . "\t" . '%12d'                                                                      # album_id - let's set this to 0 explicitly
      . "\t" . '%12d'                                                                      # set this to 0 as well
      . "\t" . RPS::ArtistRoyalty::Fast::Mapped::Data::kTypeTransaction . "\t" . '%12d'    # and this
      . "\t" . '%12d'       # and this.  These first 6 fields are shared amongst all types.
      . "\t" . '%1d'        # crossedflag, which I believe is meaningless here
      . "\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 NULL (i.e \N)
      . "\n";

    print $outFD sprintf( $gFormatString,
        $transaction->[ RPS::ArtistRoyalty::Fast::Static::ArtistPayeePendingTransactions::kArtistPayeeID() ],
        0,
        0,
        0,
        0,
        0,
        $transaction->[ RPS::ArtistRoyalty::Fast::Static::ArtistPayeePendingTransactions::kPendingTransactionID() ],
        $transaction->[ RPS::ArtistRoyalty::Fast::Static::ArtistPayeePendingTransactions::kAmount() ],
        $transaction->[ RPS::ArtistRoyalty::Fast::Static::ArtistPayeePendingTransactions::kMemo() ],
        $transaction->[ RPS::ArtistRoyalty::Fast::Static::ArtistPayeePendingTransactions::kCheckNumber() ],
        $transaction->[ RPS::ArtistRoyalty::Fast::Static::ArtistPayeePendingTransactions::kTypeCode() ],
        nullOrQuote( $transaction->[ RPS::ArtistRoyalty::Fast::Static::ArtistPayeePendingTransactions::kDate() ] ),
    );

}

sub nullOrQuote {
    my ($string) = @_;

    if ( !$string || 0 == $string || 0 == length($string) ) {
        return '\N';
    }
    return $string;

    #    return '"' . escQuotes($string) . '"';
}

1;
