package RSApache::Response::DownloadText;

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;

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

    $self->{fileHandle}  = $fh;
    $self->{contentType} = $contentType;
    $self->{fileName}    = $fileName;
}

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

    my $filename = $self->{fileName};
    $apache->headers_out->set( 'Content-Disposition' => "attachment; filename=\"$filename\"" );

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

    #$apache->send_fd($self->{fileHandle});

    # if there is a line feed without a carriage return,
    # let's add a carriage return

    my $fh = $self->{fileHandle};

    while (<$fh>) {
        $_ =~ s/(?<!\r)\n/\r\n/g;
        print $_;
    }

    close $self->{fileHandle};

    return OK;
}

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