#------------------------------------------------------------
# Copyright (C) 2006 RoyaltyShare, Inc.   All Rights Reserved
# $Id$
#------------------------------------------------------------
package RPS::Mechanical::CA::Command::DownloadCMRRA;
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::Mechanical::CA::CMRRA;
use RPS::Mechanical::Command::Download;

use base 'RPS::Command';

use RSApache::Response::DownloadZipDirectory;

sub area { return 'ca_mechanical'; }
sub cmd  { return 'cmrra'; }

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

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

sub _getPrettyFileName {
    my ( $self, $statement ) = @_;
    return RPS::Statement::Mechanical::CA::CMRRA->PrettyStatementFileNameFromDBItem($statement);
}

sub _getOriginalFileName {
    my ( $self, $statement ) = @_;
    return RPS::Statement::Mechanical::CA::CMRRA->StatementFileNameFromDBItem($statement);
}

sub _getPrettyStatementExcelFileName {
    my ( $self, $runID, $publisherID ) = @_;
    return RPS::Statement::Mechanical::CA::CMRRA->PrettyStatementExcelFileNameFromDBItem($runID);
}

sub _getOriginalStatementExcelFileName {
    my ( $self, $runID, $publisherID ) = @_;
    return RPS::Statement::Mechanical::CA::CMRRA->StatementExcelFileNameFromDBItem( $runID, $publisherID );
}

sub _getPrettySummaryExcelFileName {
    my ( $self, $runID, $publisherID ) = @_;
    return RPS::Statement::Mechanical::CA::CMRRA->PrettySummaryExcelFileNameFromDBItem($runID);
}

sub _getOriginalSummaryExcelFileName {
    my ( $self, $runID, $publisherID ) = @_;
    return RPS::Statement::Mechanical::CA::CMRRA->SummaryExcelFileNameFromDBItem( $runID, $publisherID );
}

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 );

    # Need to know which publishers are agents
    #
    my %agentList;

    my $agents = RPS::DB::Item::CAPublisher->GetAllAgents();
    while ( $agents->hasNext() ) {
        my $agent = $agents->next();
        $agentList{ $agent->ca_publisher_id } = $agent->publisher_name;
    }

    # 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");

        my $publisherID = $statement->ca_publisher_id;

        if ( exists $agentList{$publisherID} ) {

            my $agentDir = $tempdir . "/" . Common::Util::clean( $agentList{$publisherID} );
            system("mkdir $agentDir");

            # Add in the Excel CMRRA Statement and the CMRRA Summary reports
            #

            my $prettyExcelStatementFileName = $self->_getPrettyStatementExcelFileName( $runID, $publisherID );
            my $origExcelStatementFileName = $self->_getOriginalStatementExcelFileName( $runID, $publisherID );

            system("ln -s $baseFilePath/$origExcelStatementFileName $agentDir/$prettyExcelStatementFileName");

            my $prettyExcelSummaryFileName = $self->_getPrettySummaryExcelFileName( $runID, $publisherID );
            my $origExcelSummaryFileName = $self->_getOriginalSummaryExcelFileName( $runID, $publisherID );

            system("ln -s $baseFilePath/$origExcelSummaryFileName $agentDir/$prettyExcelSummaryFileName");

        }
    }

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

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

1;
