package RSApache::Response::XSLT_XML;

use strict;
use warnings;

use Apache2::Const qw(OK);

use lib '/app/tools/common/lib';
use Common::WriteXML;
use Common::Assert;
use RSApache::Response::XML;

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

use Data::Dumper;

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

    $self->{xml}  = Common::WriteXML::GetXMLString($xmlHash);
    $self->{file} = $xslFile;
}

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

    my $xml_parser  = new XML::LibXML();
    my $xslt_parser = new XML::LibXSLT();

    my $xsl_source = $xml_parser->parse_file( $self->{file} );
    assert($xsl_source);
    my $xml_source = $xml_parser->parse_string( $self->{xml} );
    assert($xml_source);
    my $stylesheet = $xslt_parser->parse_stylesheet($xsl_source);
    die "no stylesheet produced: file = " . $self->{file} if !$stylesheet;

    $apache->content_type("application/xml");

    # $apache->content_type("text/xml");

    $apache->err_header_out( 'Pragma'        => 'no-cache' );
    $apache->err_header_out( 'Cache-control' => 'no-cache' );
    $apache->send_http_header();

    my $result = $stylesheet->transform($xml_source);
    print $stylesheet->output_string($result);

    return OK;
}

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

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

    return OK;
}

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

