#!/usr/bin/perl
#------------------------------------------------------------
# Copyright (C) 2009 RoyaltyShare, Inc.   All Rights Reserved
# $Id$
#------------------------------------------------------------
use strict;

use Getopt::Std;

use lib '/app/tools/rps/lib';
use RPS::Sale::Report;
use RPS::Sale::Report::EMIPulse;

use lib '/app/tools/rps/lib';
use RPS::File::File;

use lib '/app/tools/common/lib';
use Common::NumericFormat;

# special case clients
use constant WMG                 => 21;
use constant KOCH                => 7;
use constant KED                 => 8;
use constant RNT                 => 27;
use constant EMI                 => 338;
use constant kMaxTextReportLines => 999999;

# Allow tuning of the verbosity of our output.
#
my $gVerbosityLevel = 1;

#$|++;
#open(STDERR, ">>/app/shared/sale_report/report.log") unless (-t STDIN && -t STDOUT);
_report( scalar localtime() . " - running with args '@ARGV'" );

my %opt;
getopts( 'p:c:a:re', \%opt );

my $client_id = $opt{c};
my $period_id = $opt{p};
my $atomic    = $opt{a};

usage("missing client_id") unless ( defined $client_id );
usage("missing period_id") unless ( defined $period_id );

my $appSingleton = Common::RSApp->new( clientID => $client_id );

if ( EMI == $client_id ) {
    gen_report_emi($period_id) if ( $opt{r} || !$opt{e} );
} else {
    gen_report( $client_id, $period_id ) if ( $opt{r} || !$opt{e} );
}

gen_recon( $client_id, $period_id, $atomic ) if ( $opt{e} || !$opt{r} );

gen_billing( $client_id, $period_id, $atomic ) if ( !$opt{e} && !$opt{r} );

sub gen_report_emi {
    my ($periodID) = @_;
    my $report = RPS::Sale::Report::EMIPulse->new( periodID => $periodID );
    if ( $report->exists() ) {
        _report( $report->filename() . " exists" );
        return;
    }

    $report->createReport();
}

sub gen_report {
    my $client_id = shift;
    my $period_id = shift;

    # defaults to file type "royalty" (tab)
    my $src_file = RPS::Sale::Report->GetRoyaltyReportFile( client_id => $client_id, period_id => $period_id );

    if ( -f $src_file ) {
        _report("$src_file exists");
        return;
    }

    if ( $client_id == WMG ) {
        _gen_royalty_report_WMG($src_file);
        return;
    }

    # perl -MSale::Report -e "print Sale::Report->CreateRoyaltyReport(client_id => N, period_id => 0)"

    # JPK - CreateRoyaltyReport will now return the number of lines in the text file.
    # We'll use that later to decide whether to create the Excel version.
    #
    my $lineCount = RPS::Sale::Report->CreateRoyaltyReport( client_id => $client_id, period_id => $period_id );
    unless ($lineCount) {
        _report("Error: Report creation failed");
        return;
    }

    _report("Report created: $src_file");

    if ( $client_id == KOCH || $client_id == KED ) {

        # perl -MSale::Report -e "print Sale::Report->CreateRoyaltyReportKOCHRecords(client_id => N, period_id => 0, src_file => SRC)"
        my $csv_file =
          RPS::Sale::Report->CreateRoyaltyReportKOCHRecords( client_id => $client_id, period_id => $period_id, src_file => $src_file );
        _report("Accounting Report created: $csv_file") if ( -e $csv_file );
    } elsif ( $client_id == RNT ) {

        # perl -MSale::Report -e "print Sale::Report->CreateRoyaltyReportConsolidation(client_id => N, period_id => 0)"
        my $tsv_file = RPS::Sale::Report->CreateRoyaltyReportConsolidation( client_id => $client_id, period_id => $period_id );
        _report("Consolidation Report created: $tsv_file") if ( -e $tsv_file );
    }

    # perl -MSale::Report -e "print Sale::Report->CreateRoyaltyReportExcel(client_id => N, period_id => 0, src_file => SRC)"

    # JPK - Don't attempt to create the excel version of the report if the source text file is huge.
    #
    if ( kMaxTextReportLines > $lineCount ) {
        my $xls_file =
          RPS::Sale::Report->CreateRoyaltyReportExcel( client_id => $client_id, period_id => $period_id, src_file => $src_file );
        _report("Report created: $xls_file") if ( -e $xls_file );
    }

    # who really needs the xml file anyway?
    #
    # my $xml_file = Sale::Report->CreateRoyaltyReportXML($src_file, $period_id);
    # print "Report created: $xml_file \n" if(-e $xml_file);
}

sub gen_recon {
    my ( $client_id, $period_id, $atomic ) = @_;
    my $tempSettings = Common::NumericFormat::TemporarySettings( showThousandsFlag => 0 );

    if ( $client_id == WMG ) {
        $atomic = RPS::File::Files::GetAtomicByPeriod( WMG, $period_id ) unless defined $atomic;
        if ( $atomic < 0 ) {
            _report("can't run recon with mixed atomic settings in one period");
            return;
        }
    }
    my $xls_file_recon =
      RPS::Sale::Report->GetRoyaltyReportFile( client_id => $client_id, period_id => $period_id, file_type => 'reconciliation' );

    # typically, koch/ked need this run on the current open period (0) so use
    # the following one-liner from /app/tools/sale_import/lib to generate just
    # the recon report
    # perl -MSale::Report -e "print Sale::Report->CreateReconciliationReport(client_id => N, period_id => 0)"
    if (   !-f $xls_file_recon
        && !RPS::Sale::Report->CreateReconciliationReport( client_id => $client_id, period_id => $period_id, atomic => $atomic ) ) {
        _report("Error: Recon Report creation failed");
        return;
    }
    _report("Recon Report created: $xls_file_recon") if ( -e $xls_file_recon );
}

sub gen_billing {
    my ( $client_id, $period_id, $atomic ) = @_;
    my $tempSettings = Common::NumericFormat::TemporarySettings( showThousandsFlag => 0 );

    my $xls_file_billing =
      RPS::Sale::Report->GetRoyaltyReportFile( client_id => $client_id, period_id => $period_id, file_type => 'billing' );

    if (   !-f $xls_file_billing
        && !RPS::Sale::Report->CreateBillingReport( client_id => $client_id, period_id => $period_id, atomic => $atomic ) ) {
        _report("Error: Billing Report creation failed");
        return;
    }
    _report("Billing Report created: $xls_file_billing") if ( -e $xls_file_billing );
}

sub _gen_royalty_report_WMG {
    my $out_file = shift;

    my $files = RPS::File::Files->new( client_id => $client_id );
    my $count = $files->GetByPeriod( period_id => $period_id, filter_type => 'atomic', filter_value => 0 );
    my ( $file_name, $file_ext );

    if ($count) {
        _report("$count subscription files to process");
        $file_ext = 'tab';

        while ( ( my $fileObj = $files->GetNext() ) ) {
            my $file_id = $fileObj->FileID;
            _report("processing $file_id ...");
            if ( $file_name = RPS::Sale::Report->CreateRoyaltyReportWMG( client_id => WMG, period_id => $period_id, file_id => $file_id ) )
            {
                _report("success - $file_name");
            } else {
                _report("failure");
            }
        }
    }

    # no subscription type files so check for wireless
    elsif ( $count = $files->GetByPeriod( period_id => $period_id, filter_type => 'atomic', filter_value => 1 ) ) {
        _report("$count wireless files to process");
        $file_ext = 'txt';

        while ( ( my $fileObj = $files->GetNext() ) ) {
            my $file_id = $fileObj->FileID;
            _report("processing $file_id ...");
            if ( $file_name =
                RPS::Sale::Report->CreateWirelessRoyaltyReportWMG( client_id => WMG, period_id => $period_id, file_id => $file_id ) ) {
                _report("success - $file_name");
            } else {
                _report("failure");
            }
        }
    } else {
        _report("no files to process (subscription or wireless)");
        return;
    }

    unless ($file_name) {
        _report("cannot zip sales files");
        return;
    }

    $file_name = reverse $file_name;
    $file_name =~ s/^[^\/]+\///;
    $file_name = reverse $file_name;
    $out_file =~ s/\.\w+$//;
    system("zip -j $out_file $file_name/*.$file_ext");
    _report("zip failed") unless ( -f "$out_file.zip" );

    return 1;
}

sub usage {
    my $err = shift;

    print "$err\n\n" if ($err);

    print <<EOF;
usage: $0 [-re -a ATOMIC] -c CLIENT_ID -p PERIOD_ID

-r           : runs only the royalty report
-e           : runs only the reconciliation report
-a [0|1]     : 0 = non-atomic, 1 = atomic (currently only applies to WMG so for all others leave blank or set to 0)
-c CLIENT_ID : is the client ID
-p PERIOD_ID : is the period ID
EOF

    exit;
}

sub _report {
    my ( $string, $verbosity ) = @_;
    $verbosity = 1 unless defined $verbosity;

    if ( $gVerbosityLevel >= $verbosity ) {
        Common::Log::Print($string);
    }
}
