#------------------------------------------------------------
# Copyright (C) 2006 RoyaltyShare, Inc.   All Rights Reserved
# $Id$
#------------------------------------------------------------
package BookPub::Tracker::Command::DownloadFile;
use strict;
use warnings;

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

use lib '/app/tools/bookpub/lib';
use BookPub::Tracker::File;
use BookPub::Tracker::Command::Main;

use base 'BookPub::Command';

sub cmd      { return "saveas"; }
sub area     { return "tracker"; }
sub pageName { return "Download File"; }

use constant kTemplate => '/app/tools/bookpub/templates/tracker.xsl';

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

    # Give any inherited methods the first crack at this.
    # (This checks for login and basic access permissions).
    #
    my $response = $self->SUPER::execute();
    return $response if $response;

    my $fileID = $self->getParam('file');
    my $file = BookPub::Tracker::File->new( fileID => $fileID );
    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 {
        Common::Log::Print "--- cannot download file $fileOnDisk\n";

        # Redirect back to the tracker page.
        # !!! Let's do a 'fake' redirect.
        my $newCmd = BookPub::Tracker::Command::Main->new( period => $self->getParam('period') );
        $newCmd->addMessageXML( type => "error", code => "download_unavailable" );
        $response = $newCmd->execute();
    }

    return $response;
}

1;
