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

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

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

use lib '/app/tools/rps/lib';
use RPS::Statement::Label::PDF;
use RPS::Statement::Label::Report;
use RPS::DB::Item::LabelRoyaltyRun;
use RPS::DB::Item::LabelRoyaltyStatement;
use RPS::Command;
use base 'RPS::Command';

use RSApache::Response::DownloadZipDirectory;

sub area { return 'label_royalty'; }
sub cmd  { return 'pdf'; }

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

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

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

    # 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 $basePDFFilePath    = RPS::Statement::Label::PDF::StatementPathFromRunID($runID);
    my $baseReportFilePath = RPS::Statement::Label::Report::ReportPathFromRunID($runID);
    my $allStatements      = RPS::DB::Item::LabelRoyaltyStatement->GetByLabelRoyaltyRunID($runID);

    while ( my $statement = $allStatements->next() ) {
        my $prettyPDFFileName = RPS::Statement::Label::PDF::PrettyStatementFileNameFromDBItem($statement);
        my $uglyPDFFileName   = RPS::Statement::Label::PDF::StatementFileNameFromDBItem($statement);
        system("ln -s $basePDFFilePath/$uglyPDFFileName $tempdir/$prettyPDFFileName");

        my $prettyReportFileName = RPS::Statement::Label::Report::PrettyReportFileNameFromDBItem($statement);
        my $uglyReportFileName   = RPS::Statement::Label::Report::ReportFileNameFromDBItem($statement);
        system("ln -s $baseReportFilePath/$uglyReportFileName $tempdir/$prettyReportFileName");
    }

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

1;
