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

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

    # We'll store the CMRRA excel statement 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->PrettyStatementExcelFileNameFromDBItem( $runID, $publisherID );
    my $uglyFileName   = RPS::Statement::Mechanical::CA::CMRRA->StatementExcelFileNameFromDBItem( $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;
