package RPS::Mechanical::US::Command::DownloadManualStatements;

use strict;
use warnings;

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

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

use lib '/app/tools/rps/lib';
use RPS::DB::Item::MechanicalStatement;
use RPS::Statement::Mechanical::US::PDF;
use RPS::Statement::Mechanical::US::Text;

use RPS::Mechanical::Command::Download;
use base 'RPS::Mechanical::Command::DownloadManualStatements';

sub area { 'mechanical' }
sub cmd  { 'manual' }


sub _baseFilePath {
    my ( $self, $runID ) = @_;
    return RPS::Statement::Mechanical::US::PDF->StatementPathFromRunID($runID);
}

sub _getStatementCollection {
    my ( $self, $runID ) = @_;
    return RPS::DB::Item::MechanicalStatement->GetManualByMechanicalRunID($runID);
}

sub _getZipFileName {
    my ( $self, $runID ) = @_;
    return "us_publisher_manual_run_$runID.zip";
}

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

    my $clientID = Common::RSApp::GetClientID();
    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( "/tmp/publisher_" . $clientID . "_" . $runID . "XXXXXXXX", CLEANUP => 1 );

    # Loop through all the statements, and populate the temp directory with symlinks
    my $baseFilePath  = $self->_baseFilePath($runID);

    # We only want statements for payees that are set for manual distribution
    my $allStatements = $self->_getStatementCollection($runID);
    while ( my $oStatement = $allStatements->next() ) {
        my $prettyFileName = RPS::Statement::Mechanical::US::PDF->PrettyStatementFileNameFromDBItem($oStatement);
        my $uglyFileName   = RPS::Statement::Mechanical::US::PDF->StatementFileNameFromDBItem($oStatement);
        system("ln -s $baseFilePath/$uglyFileName $tempdir/$prettyFileName");

        $prettyFileName = RPS::Statement::Mechanical::US::Text->PrettyStatementFileNameFromDBItem($oStatement);
        $uglyFileName   = RPS::Statement::Mechanical::US::Text->StatementFileNameFromDBItem($oStatement);
        system("ln -s $baseFilePath/$uglyFileName $tempdir/$prettyFileName");
    }

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

    return $response;
}


1;
