#------------------------------------------------------------
# Copyright (C) 2006 RoyaltyShare, Inc.   All Rights Reserved
# $Id$
#------------------------------------------------------------
package BookPub::Tracker::Command::DownloadPriceExceptionsReport;
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 BookPub::Sale::Report::PriceExceptions::AllFiles;

use base 'BookPub::Command';

sub cmd      { return "price_exceptionsdl"; }
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 $tempSettings = Common::NumericFormat::TemporarySettings( showThousandsFlag => 0 );

    my $report     = BookPub::Sale::Report::PriceExceptions::AllFiles->new();
    my $fileOnDisk = $report->filePath();

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

        $response = RSApache::Response::Download->new( $fh, 'application/octet-stream', $report->fileName() );
    } 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 => 0 );
        $newCmd->addMessageXML( type => "error", code => "download_unavailable" );
        $response = $newCmd->execute();
    }

    return $response;
}

1;
