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

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

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

use lib '/app/tools/rps/lib';
use RPS::Statement::Mechanical::CA::Text;
use base 'RPS::Mechanical::Command::Download';

use RSApache::Response::Download;

sub area { return 'ca_mechanical'; }
sub cmd  { return 'export_summary'; }

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

    # We'll store the CMRRA agent report in the same directory as the
    # mechanical statements.
    #
    return RPS::Statement::Mechanical::CA::Text->StatementPathFromRunID($runID);
}

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

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

    my $runLabel = RPS::Statement::Mechanical::CA::Text->_RunLabelClean($runID);
    return "CMRRA_Summary_" . $runLabel . ".xlsx";
}

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

    # This must match the filename generated by the createCAMechanicalSummaryReportExcel.pl script.
    return "cmrra_agent_summary_run_" . $runID . ".xlsx";
}

# 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::Handle;
    open( $fh, "$fullPath" ) or die "ERROR: Unable to open $fullPath for reading: $!";

    my $contentType = 'application/octet-stream';
    my $response = RSApache::Response::Download->new( $fh, $contentType, $prettyFileName );

    return $response;
}

1;
