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

package RPS::ArtistRoyalty::Fast::Script::MapLicenseIncome;

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::LicenseIncomeSales;

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 License Income Sales");
    my $licenseIncomeSales =
      RPS::ArtistRoyalty::Fast::Static::LicenseIncomeSales->GetLicenseIncomeSales( $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 license income sales...");
    foreach my $line (@$licenseIncomeSales) {
        Log->info( "\n\nLICENSE INCOME LINE:", $line );

        my @array = split( "\t", $line );
        my $licenseIncome = \@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, $licenseIncome );
    }
}

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, $licenseIncome ) = @_;

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

    my $effectiveRevenue = Common::RSMath::round(
        $licenseIncome->[RPS::ArtistRoyalty::Fast::Static::LicenseIncomeSales::kRevenue] *
          ( $licenseIncome->[RPS::ArtistRoyalty::Fast::Static::LicenseIncomeSales::kRate] / 100 ),
        2
    );

    my $gFormatString = '%12d'                                                               # payee_id
      . "\t" . '%12d'                                                                        # album_id
      . "\t" . '%12d'                                                                        # artist_contract_id
      . "\t" . RPS::ArtistRoyalty::Fast::Mapped::Data::kTypeLicenseIncome . "\t" . '%12d'    # track_id
      . "\t" . '%12d'    # term_id (a no-op just to keep stuff sorted correctly)
      . "\t" . '%1d'     # crossedflag

      . "\t" . '%12d'    # license income id
      . "\t" . '%12d'    # license income type id

      . "\t" . '%20.08f' # rate
      . "\t" . '%12d'    # units
      . "\t" . '%20.08f' # revenue
      . "\t" . '%20.08f' # net revenue
      . "\t" . '"%s"'    # memo
      . "\t" . '%12d'    # sale_id

      . "\n";

    # I think we've got 283 chars per sale line, including the line feed.
    # S0, 283 - 79 = 203 spaces to pad plus 1 carriage return.

    print $outFD sprintf( $gFormatString,
        $licenseIncome->[ RPS::ArtistRoyalty::Fast::Static::LicenseIncomeSales::kArtistPayeeID() ],
        $licenseIncome->[ RPS::ArtistRoyalty::Fast::Static::LicenseIncomeSales::kAlbumID() ],
        $licenseIncome->[ RPS::ArtistRoyalty::Fast::Static::LicenseIncomeSales::kArtistContractID() ],
        $licenseIncome->[ RPS::ArtistRoyalty::Fast::Static::LicenseIncomeSales::kTrackID() ],
        0,
        $licenseIncome->[ RPS::ArtistRoyalty::Fast::Static::LicenseIncomeSales::kCrossed() ],
        $licenseIncome->[ RPS::ArtistRoyalty::Fast::Static::LicenseIncomeSales::kLicenseIncomeID() ],
        $licenseIncome->[ RPS::ArtistRoyalty::Fast::Static::LicenseIncomeSales::kLicenseIncomeTypeID() ],
        $licenseIncome->[ RPS::ArtistRoyalty::Fast::Static::LicenseIncomeSales::kRate() ],
        $licenseIncome->[ RPS::ArtistRoyalty::Fast::Static::LicenseIncomeSales::kUnits() ],
        $licenseIncome->[ RPS::ArtistRoyalty::Fast::Static::LicenseIncomeSales::kRevenue() ],
        $effectiveRevenue,
        $licenseIncome->[ RPS::ArtistRoyalty::Fast::Static::LicenseIncomeSales::kMemo() ],
        $licenseIncome->[ RPS::ArtistRoyalty::Fast::Static::LicenseIncomeSales::kSaleID() ],
    );

}

1;
