package RSApache::Response::DownloadIterator;

use strict;
use warnings;

use Apache2::Const qw(OK);

use lib ('/app/tools/common/lib');
use RSApache::Response;
use base 'RSApache::Response';

use Data::Dumper;

# An 'iterator' in this case is an object that implements these two method:
# hasNext();
# next();

sub _init {
    my ( $self, $iterator, $contentType, $fileName, $fileSize ) = @_;
    $contentType = 'application/octet-stream' unless $contentType;
    $fileName    = 'RoyaltyShareFileDownload' unless $fileName;

    $self->{iterator}    = $iterator;
    $self->{contentType} = $contentType;
    $self->{fileName}    = $fileName;
    $self->{fileSize}    = $fileSize;
}

sub respond {
    my ( $self, $apache ) = @_;

    my $filename = $self->{fileName};
    if ( $self->{fileSize} ) {
        $apache->headers_out->add( 'Content-Length' => $self->{fileSize} );
    }

    $apache->headers_out->add( 'Content-Disposition' => "attachment; filename=\"$filename\"" );

    $apache->send_http_header( $self->{contentType} );

    while ( $self->{iterator}->hasNext() ) {
        $self->_outputLine( $self->{iterator}->next() );
    }

    return OK;
}

sub _outputLine {
    my ( $self, $line ) = @_;
    print $line;
}

###
1;    # Play nicely.
###
