#------------------------------------------------------------
# Copyright (C) 2009 RoyaltyShare, Inc.   All Rights Reserved
#------------------------------------------------------------
package Support::BookPub::Command::DownloadFile;
use strict;
use warnings;
use Data::Dumper;

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

use lib '/app/tools/bookpub/lib';
use BookPub::RDAS::Request::POSData;
use BookPub::POS::Tracker::File;
use Support::BookPub::Command::POSFeed;

use lib '/app/tools/support/lib';

use base 'Support::Command';

sub cmd  { return 'pos_retry' }
sub area { return 'bookpub'; }

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

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

    my $posFileID = $self->getParam('POSFileID');
    assert($posFileID);

    my $file = BookPub::POS::Tracker::File->new( posFileID => $posFileID );
    assert($file);

    my $fileOnDisk = $file->FileDir . "/" . $file->FileName;

    Common::Log::Print("checking file on disk:  $fileOnDisk");

    if ( -f $fileOnDisk ) {
        open my $fh, "<$fileOnDisk";

        $response = RSApache::Response::Download->new( $fh, 'application/octet-stream', $file->OrigFileName );
    } else {
        Log->error("--- cannot download file $fileOnDisk");
        die "File does not exist $fileOnDisk";

        # Redirect back to the tracker page.
        # !!! Let's do a 'fake' redirect.
        my $newCmd = Support::BookPub::Command::POSFeed->new();
        $newCmd->addMessageXML( type => "error", code => "download_unavailable" );

        $response = $newCmd->execute();
    }

    return $response;
}

1;
