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

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

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

    my $runLabel = RPS::Statement::Artist::PDF::_runLabelClean($runID);
    return "Album_Balances_" . $runLabel . ".txt";
}

sub _getOriginalFileName
{
    my ($self, $runID) = @_;
    # This must match the filename generated by the createArtistAlbumBalancesExportReportText script.
    return "ab_export_run_" . $runID . ".txt";
}

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::DownloadText->new($fh, $contentType, $prettyFileName, $fileSize);
    return $response;
}

1;
