#------------------------------------------------------------
# Copyright (C) 2006 RoyaltyShare, Inc.   All Rights Reserved
# $Id$
#------------------------------------------------------------
package RPS::Mechanical::US::Command::DownloadExportText;
use strict;
use warnings;

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

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

use lib '/app/tools/rps/lib';
use RPS::Statement::Mechanical::US::Text;
use base 'RPS::Mechanical::Command::DownloadText';

use RSApache::Response::DownloadText;

sub area { return 'mechanical'; }
sub cmd  { return 'export_text'; }

sub _baseFilePath
{
    my ($self, $runID) = @_;
    # We'll store the royalty data export report in the same directory as the
    # mechanical statements.
    #
    return RPS::Statement::Mechanical::US::Text->StatementPathFromRunID($runID);
}

sub _getStatementCollection
{
    my ($self, $runID) = @_;
    return undef;
}

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

    my $runLabel = RPS::Statement::Mechanical::US::Text->_RunLabelClean($runID);
    return "Royalty_data_export_" . $runLabel . ".txt";
}

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

# We override execute() since we're only downloading one file instead of
# of a bunch of statements.
#
sub execute
{
    my ($self) = @_;

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

    my $baseFilePath   = $self->_baseFilePath($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];
    my $contentType = 'application/octet-stream';
    my $response = RSApache::Response::DownloadText->new($fh, $contentType, $prettyFileName, $fileSize);

    return $response;

    
}

1;
