#------------------------------------------------------------
# Copyright (C) 2006 RoyaltyShare, Inc.   All Rights Reserved
# $Id$
#------------------------------------------------------------
package RPS::Mechanical::Command::Download;
use strict;
use warnings;

use IO::Handle;
use File::Temp;

use lib '/app/tools/common/lib';
use Common::FormObject;
use Common::Assert;

use lib '/app/tools/rps/lib';
use RPS::Command;
use base 'RPS::Command';

use RSApache::Response::DownloadZipDirectory;

sub _baseFilePath {
    my ( $self, $runID ) = @_;
    assert( 0, 'override this' );
}

sub _getStatementCollection {
    my ( $self, $runID ) = @_;
    assert( 0, 'override this' );
}

sub _getPrettyFileName {
    my ( $self, $statement ) = @_;
    assert( 0, 'override this' );
}

sub _getOriginalFileName {
    my ( $self, $statement ) = @_;
    assert( 0, 'override this' );
}

sub _getZipFileName {
    my ( $self, $runID ) = @_;
    assert( 0, 'override this' );
}

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

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

    my $runID = $self->getParam('MechanicalRunID');

    # We need to create a temporary directory, and fill it with symlinks.
    # Each symlink will have the 'pretty' statement filename, and point
    # to the real statement.
    # This will allow the zip utility to create an archive that contains the
    # pretty names, while the files on the server retain the boring old names.
    #

    # We pass CLEANUP => 1 so that the directory (and all its contents) will get
    # deleted automatically, presumably when $tempdir finally goes out of scope.
    # !!! Hopefully the timing will all be ok with this.
    #
    my $tempdir = File::Temp::tempdir( CLEANUP => 1 );

    # Loop through all the statements, and populate the temp directory with symlinks
    #
    my $baseFilePath  = $self->_baseFilePath($runID);
    my $allStatements = $self->_getStatementCollection($runID);
    while ( my $statement = $allStatements->next() ) {
        my $prettyFileName = $self->_getPrettyFileName($statement);
        my $uglyFileName   = $self->_getOriginalFileName($statement);

        # Create the symlink.
        # Using a symlink allows us to rename the file, and is obviously
        # a lot faster than copying the data.
        #
        system("ln -s $baseFilePath/$uglyFileName $tempdir/$prettyFileName");
    }

    # Download it!
    #
    my $contentType = 'application/octet-stream';
    my $zipFileName = $self->_getZipFileName($runID);
    $response = RSApache::Response::DownloadZipDirectory->new( $tempdir, $contentType, $zipFileName );
    return $response;
}

1;
