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

use IO::File;

use lib '/app/tools/rps/lib';
use RPS::Statement::Label::Report;
use RPS::DB::Item::LabelRoyaltyStatement;
use RPS::DB::Item::LabelRoyaltyRun;

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

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

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


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

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

    my $id = $self->getParam("LabelStatementID");
    my $statementData = RPS::DB::Item::LabelRoyaltyStatement->Lookup(label_royalty_statement_id => $id);
    my $runID = $statementData->label_royalty_run_id;

    my $prettyFilename = RPS::Statement::Label::Report::PrettyReportFileNameFromID($id);
    my $filename = RPS::Statement::Label::Report::ReportFileNameFromID($id);
    my $path = RPS::Statement::Label::Report::ReportPathFromRunID($runID);

    my $fullPath = $path . $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::DownloadText->new($fh, $contentType, $prettyFilename, $fileSize);
	return $response;
}

1;
