#------------------------------------------------------------
# Copyright (C) 2011 RoyaltyShare, Inc.   All Rights Reserved
#------------------------------------------------------------
package RPS::Report::Dynamic::Command::Download;
use strict;
use warnings;


use Data::Dumper;

use lib '/app/tools/common/lib';
use RSApache::Response::Download;
use Common::Util;
use Common::Assert;

use lib '/app/tools/rps/lib';
use RPS::CommandLog;
use RPS::Report::Dynamic::Factory;

use base 'RPS::Command';

sub cmd  { return 'download'; }
sub area { return 'report'; }

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

    my $params;

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

    RPS::CommandLog::Log($self);

    my $type     = $self->getParam('Type');
    my $reportID = $self->getParam('ReportID');

    assert($type);
    assert($reportID);

    my $report = RPS::Report::Dynamic::Factory->Fetch( $reportID );
    die "TODO:  Report not found" unless( $report );

    my $fh = $report->fetch( type => $type );
    die "TODO: Could not open report type $type" unless( $fh );

    # Get the filesize, using the IO::Handle stat interface.
    #
    my @stat = $fh->stat;
    my $fileSize = $stat[7];

    my $contentType = 'application/octet-stream';

    $response = RSApache::Response::Download->new($fh, $contentType, $report->filename . ".$type", $fileSize);
    return $response;
}


1;
