#!/usr/bin/perl
use strict;

use Getopt::Std;

use lib '/app/tools/common/lib';
use Common::RSDB;
use Common::Locale;
use Common::Client;
use Common::RSApp;
use Common::Locale;

# Parse the command-line, then create the report
#
my %options;
parseCommandLine( \%options );
gen_exception_report( $options{clientID}, $options{fileName} );

sub gen_exception_report {
    my $clientID = shift;
    my $fileName = shift;

    # Instantiate the application singleton object.
    #
    my $appSingleton = Common::RSApp->new( clientID => $clientID );

    ## output to file
    if ( $fileName ne "" ) {
        open( STDOUT, ">" . $fileName . "-tmp" );
    }

    my $db = Common::RSDB->new( client_id => $clientID );
    my $dbh = $db->DBH;

    my $sql =
        "SELECT file.orig_file_name, service.service_name, sale.* FROM file, sale, service "
      . "WHERE file.file_id=sale.file_id AND file.service_id=service.service_id AND product_id IS NULL "
      . "AND file_status = 4 AND period_id = 0 "
      . "ORDER BY file.service_id, sale.file_id, sale.line_num";

    my $sth  = $dbh->prepare($sql);
    my $rows = $sth->execute();

    my $locale                 = Common::Client::Current()->Locale();
    my $baseCurrencyCodeHeader = lc( $locale->currencyFormat()->currencyCode() ) . "_ext_price";

    my $header = join(
        "\t", qw(file_name
          service
          sale_id
          file_id
          product_type
          format_type
          media_type
          date_begin
          date_end
          service_product_id
          client_product_id
          upc
          isrc
          artist_name
          album_name
          track_name
          label_name
          track_num
          gross_units
          returns
          net_units
          price_ext
          total_revenue
          currency_code
          conversion_rate
          country_code
          line_num
          import_status)
    );

    $header .= "\t" . $baseCurrencyCodeHeader;

    print $header . "\n";

    while ( my $row = $sth->fetchrow_hashref() ) {
        my ( $grossUnits, $returns, $netUnits, $price, $totalRevenue, $extPrice );
        if ( $row->{product_type} ne 'A' && $row->{product_type} ne 'T' ) {
            # physical sales calculations
            $grossUnits   = $row->{sales};
            $returns      = $row->{returns};
            $netUnits     = $row->{sales} - $row->{returns};
            $price        = '';
            $totalRevenue = $row->{total_revenue};
            $extPrice     = $row->{total_revenue} * $row->{conversion_rate};
        } else {
            # digital sales calculations
            $grossUnits   = '';
            $returns      = '';
            $netUnits     = $row->{units};
            $price        = $row->{price};
            $totalRevenue = $row->{units} * $row->{price};
            $extPrice     = $totalRevenue * $row->{conversion_rate};
        }
        print $row->{orig_file_name} . "\t"
          . $row->{service_name} . "\t"
          . $row->{sale_id} . "\t"
          . $row->{file_id} . "\t"
          . $row->{product_type} . "\t"
          . $row->{format_type} . "\t"
          . $row->{media_type} . "\t"
          . _formatDate( $row->{date_begin} ) . "\t"
          . _formatDate( $row->{date_end} ) . "\t"
          . $row->{service_product_id} . "\t"
          . $row->{client_product_id} . "\t"
          . $row->{upc} . "\t"
          . $row->{isrc} . "\t"
          . $row->{artist_name} . "\t"
          . $row->{album_name} . "\t"
          . $row->{track_name} . "\t"
          . $row->{label_name} . "\t"
          . $row->{track_num} . "\t"
          . $grossUnits . "\t"
          . $returns . "\t"
          . $netUnits . "\t"
          . _formatNumber($price) . "\t"
          . _formatNumber($totalRevenue) . "\t"
          . $row->{currency_code} . "\t"
          . _formatNumber( $row->{conversion_rate} ) . "\t"
          . $row->{country_code} . "\t"
          . $row->{line_num} . "\t"
          . $row->{import_status} . "\t"
          . _formatNumber($extPrice) . "\n";
    }

    ## output to file
    if ( $fileName ne "" ) {
        close STDOUT;
        system("mv ${fileName}-tmp $fileName");
    }
}

sub _formatNumber {
    my ($value) = @_;

    # Turning this off for now.  We're not sure if we want anything other than a "." showing up
    # as a a decimal point.
    #
    #my $tempSettings = Common::NumericFormat::TemporarySettings(showThousandsFlag => 0);
    #$value = Common::Client::Locale()->formatNumber($value);

    return $value;
}

sub _formatDate {
    my ($date) = @_;

    $date = Common::Client::Current()->Locale()->formatDate($date);

    return $date;
}

sub parseCommandLine {
    my ($settings) = @_;

    my %opt;
    getopts( 'c:f:', \%opt );

    if ( !$opt{c} || !$opt{f} ) {
        usage();
        exit(1);
    }
    $settings->{clientID} = $opt{c};
    $settings->{fileName} = $opt{f};
}

sub usage {
    print STDERR "\nusage: $0 -c <client_id> -f <file_name>\n";
    print STDERR "\n";
    print STDERR "Arguments:\n";
    print STDERR "\t-c <client_id>\tThe client_id of the client to process\n";
    print STDERR "\t-f <file_name>\tThe name for the file that is produced\n";

    return 1;
}
