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

use IO::File;

use lib '/app/tools/rps/lib';
use RPS::DB::Item::CAMechanicalStatement;
use RPS::Statement::Mechanical::CA::PDF;

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

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

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


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

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

    my $id = $pathArray[4];
    
    my $statementData = RPS::DB::Item::CAMechanicalStatement->Lookup(ca_mechanical_statement_id => $id);
    my $runID = $statementData->ca_mechanical_run_id;

    # Need to wrap a bit of abstraction around these file paths. Hard coding isn't that great...
    #
    my $prettyFileName;
    my $fileName;
    
    my $statementType = $pathArray[5];
    
    if ($statementType eq 'Label')
    {
        $prettyFileName = RPS::Statement::Mechanical::CA::PDF->PrettyLabelStatementFileNameFromDBItem($statementData);
        $fileName = RPS::Statement::Mechanical::CA::PDF->LabelStatementFileNameFromDBItem($statementData);
    }
    else
    {
        $prettyFileName = RPS::Statement::Mechanical::CA::PDF->PrettyStatementFileNameFromDBItem($statementData);
        $fileName = RPS::Statement::Mechanical::CA::PDF->StatementFileNameFromDBItem($statementData);        
    }
    
    my $fullPath = RPS::Statement::Mechanical::CA::PDF->StatementPathFromRunID($runID) . $fileName;

    my $fh = new IO::File;
    open($fh, "$fullPath") or die "ERROR: Unable to open $fullPath for reading: $!";
    
  	my $contentType = 'application/pdf';
    my @stat = $fh->stat;
    my $fileSize = $stat[7];

    $response = RSApache::Response::DownloadInline->new($fh, $contentType, $prettyFileName, $fileSize);

	return $response;
}

1;
