package RPS::ArtistRoyalty::Command::DownloadLicenseIncomePayableAuditExcel;
use strict;
use warnings;

use IO::File;
use File::Temp;

use lib '/app/tools/common/lib';
use Common::FormObject;
use Common::Log;

use lib '/app/tools/rps/lib';
use RPS::Statement::Artist::PDF;
use RPS::DB::Item::ArtistRoyaltyRun;
use RPS::DB::Item::ArtistRoyaltyStatement;
use RPS::Command;
use base 'RPS::Command';

use RSApache::Response::Download;

sub area { return 'artist_royalty'; }
sub cmd  { return 'license_income_payable_audit_excel'; }

sub _sanitizeNameForFile {
    my ($str) = @_;

    $str =~ s/[^a-zA-Z0-9]/_/g;
    $str =~ s/_+/_/g;
    $str =~ s/^_|_$//g;

    return $str;
}

sub _getPrettyFileName {
    my ( $self, $runID ) = @_;

    my ($runName, $payor) = RPS::DB::Item::ArtistRoyaltyRun->GetRunNameAndPayor($runID);
    $runName = _sanitizeNameForFile($runName);
    $payor = _sanitizeNameForFile($payor);

    return "License_Income_${runName}_${payor}_${runID}.xlsx";
}

sub _getOriginalFileName {
    my ( $self, $runID ) = @_;

    my ($runName, $payor) = RPS::DB::Item::ArtistRoyaltyRun->GetRunNameAndPayor($runID);
    $runName = _sanitizeNameForFile($runName);
    $payor = _sanitizeNameForFile($payor);

    # This must match the filename generated by the createLicenseIncomePayableAuditReport.
    return "License_Income_${runName}_${payor}_${runID}.xlsx";
}

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

    my $runID = $self->getParam('RoyaltyRunID');

    my $baseFilePath   = RPS::Statement::Artist::PDF::StatementPathFromRunID($runID);
    my $prettyFileName = $self->_getPrettyFileName($runID);
    my $uglyFileName   = $self->_getOriginalFileName($runID);

    my $fullPath = $baseFilePath . $uglyFileName;
    my $fh       = new IO::File;
    open( $fh, "$fullPath" ) or die "ERROR: Unable to open $fullPath for reading: $!";

    my @stat     = $fh->stat;
    my $fileSize = $stat[7];

    # Download it!
    #
    my $contentType = 'application/octet-stream';
    my $response = RSApache::Response::Download->new( $fh, $contentType, $prettyFileName, $fileSize );
    return $response;
}

1;
