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

use base 'RPS::Command';

use RSApache::Response::Download;

sub area { return 'statement'; }
sub cmd  { return 'cmrra_summary_excel'; }

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::CMRRA->StatementPathFromRunID($runID);
}

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

    my $id = $self->getParam("MechanicalStatementID");
    my $statementData = RPS::DB::Item::CAMechanicalStatement->Lookup(ca_mechanical_statement_id => $id);
    my $runID = $statementData->ca_mechanical_run_id;
    my $publisherID = $statementData->ca_publisher_id;

    my $baseFilePath   = $self->_baseFilePath($runID);
    my $prettyFileName = RPS::Statement::Mechanical::CA::CMRRA->PrettySummaryExcelFileNameFromDBItem($runID, $publisherID);
    my $uglyFileName   = RPS::Statement::Mechanical::CA::CMRRA->SummaryExcelFileNameFromDBItem($runID, $publisherID);

    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;
