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

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

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

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

use RSApache::Response::DownloadZipDirectory;

sub area { return 'uk_mech'; }
sub cmd  { return 'text'; }

use constant kZipProg => '/usr/bin/zip';

sub execute {

    # !!! This code is not currently in use, as there is nor zip file for the text statements.
    #

    my ($self) = @_;

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

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

    # 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  = RPS::Statement::UKMechanical::McpsText::StatementPathFromRunID($runID);
    my $allStatements = RPS::DB::Item::McpsStatement->GetByRunID($runID);
    while ( my $statement = $allStatements->next() ) {
        my $prettyFileName = RPS::Statement::UKMechanical::McpsText::PrettyStatementFileNameFromDBItem($statement);
        my $uglyFileName   = RPS::Statement::UKMechanical::McpsText::StatementFileNameFromDBItem($statement);

        system("ln -s $baseFilePath/$uglyFileName $tempdir/$prettyFileName");
    }

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

1;
