package RSApache::Response::JSON;

use strict;
use warnings;

use Apache2::Const qw(OK);
use JSON::XS;

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

use RSApache::Response;
use base 'RSApache::Response';

sub _init {
    my ( $self, $output ) = @_;
    assert( defined $output );

    # if we're passed a hash ref, convert to a JSON string
    # Otherwise, just pass it along.
    #
    if ( ref($output) ) {
        $self->{output} = JSON::XS->new->ascii->pretty->allow_nonref->encode($output);
    } else {
        $self->{output} = $output;
    }
}

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

    $apache->content_type("text/plain; charset=UTF-8");

    # Instruct the browser (specifically, Internet Explorer) to NOT CACHE this response
    #
    $apache->header_out( 'Cache-Control' => 'no-cache' );
    $apache->header_out( 'Pragma'        => 'no-cache' );
    $apache->header_out( 'Expires'       => '-1' );

    $apache->send_http_header();
    print $self->{output};

    return OK;
}

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

    $apache->content_type("text/plain");
    $apache->send_http_header();
    print $self->{output};

    return OK;
}

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

