#------------------------------------------------------------
# Copyright (C) 2006 RoyaltyShare, Inc.   All Rights Reserved
# $Id$
#------------------------------------------------------------
package RPS::ArtistRoyalty::Command::DownloadRoyaltyBreakdown;
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 'royalty_breakdown_dl'; }

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

    my $runLabel = RPS::Statement::Artist::PDF::_runLabelClean($runID);
    return "Royalty_Earnings_Breakdown_" . $runLabel . "_" . $runID . ".zip";
}

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

    # This must match the filename generated by the createRoyaltyBreakdown script.
    return "artist_run_" . $runID . "_royalty_breakdown.zip";
}

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;
