package Support::DataImport::Command::Download;
use strict;
use warnings;

use File::Basename;

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

use lib '/app/tools/support/lib';
use Support::DB::Item::DataImport;
use Support::DB::Item::DataImportFile;

use base 'Support::DataImport::Command::Base';

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

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

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

    my $fileID   = $self->getParam('fileID');

    # Get the filename and path information

    my $importFile = Support::DB::Item::DataImportFile->Lookup( file_id => $fileID );
    my $filename   = $importFile->file_name;

    my $import       = Support::DB::Item::DataImport->Lookup( import_id => $importFile->import_id );
    my $baseFilePath = $import->path;

    my $fullPath = $baseFilePath . '/' . $filename;

    my $prettyFilename  = $filename; # download the file using the original name

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

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

    print STDERR "Support::DataImport::Command::Download - downloading '$fullPath' as '$prettyFilename' (filesize=$fileSize)\n";
    $response    = RSApache::Response::Download->new( $fh, $contentType, $prettyFilename, $fileSize );
    return $response;

}

1;
