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

use IO::File;

use lib '/app/tools/rps/lib';
use RPS::DB::Item::McpsStatement;
use RPS::Statement::UKMechanical::McpsPDF;

use lib '/app/tools/common/lib';
use Common::WriteXML;
use RSApache::Response::Download;
use Common::Timer;

use RPS::Command;
use RPS::CommandLog;
use base 'RPS::Command';

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


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

    my $timer = Common::Timer->new();

	my $response = $self->SUPER::execute();
	return $response if $response;

    my $id = $self->getParam("McpsStatementID");
    my $statementData = RPS::DB::Item::McpsStatement->Lookup(mcps_statement_id => $id);
    my $runID = $statementData->uk_mechanical_run_id;

    # Need to wrap a bit of abstraction around these file paths. Hard coding isn't that great...
    #
    my $prettyFileName = RPS::Statement::UKMechanical::McpsPDF::PrettyStatementFileNameFromDBItem($statementData);
    my $fileName = RPS::Statement::UKMechanical::McpsPDF::StatementFileNameFromDBItem($statementData);
    my $fullPath = RPS::Statement::UKMechanical::McpsPDF::StatementPathFromRunID($runID) . $fileName;

    my $fh = new IO::File;
    open($fh, "$fullPath") or die "ERROR: Unable to open $fullPath for reading: $!";
    
	my $contentType = 'application/octet-stream';

    my @stat = $fh->stat;
    my $fileSize = $stat[7];
    $response = RSApache::Response::Download->new($fh, $contentType, $prettyFileName, $fileSize);
	return $response;
}

1;
