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

use base 'BookPub::Command';

sub cmd      { return "currentrecon"; }
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::Reconciliation->new( periodID => 0, clientID => Common::RSApp::GetClientID() );
    my $fileOnDisk = $report->filePath();

    # We _always_ generate this dynamically.
    # !!! It might be cool if we could pass the report class a filehandle, and stream this...
    #
    unlink $fileOnDisk if ( -e $fileOnDisk );

    $report->create();

    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;
