package RSApache::Response::XSLTTemplate;

use strict;
use warnings;

use XML::LibXSLT;
use XML::LibXML;
use XML::Simple;
use Template;

use Data::Dumper;

use Apache2::Const qw(OK);

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

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

use CGI;

use Data::Dumper;

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

    my $firstPass = $self->_translateTemplate( xsltFile => $self->{file}, xml => $self->{xml} );
    my $secondPass = $self->_translateXML( xslt => $firstPass, xml => $self->{xml} );

    $apache->content_type("text/html; charset=UTF-8");
    $apache->header_out( 'Cache-Control' => 'no-cache' );
    $apache->header_out( 'Pragma'        => 'no-cache' );
    $apache->header_out( 'Expires'       => '-1' );
    $apache->send_http_header();

    print $secondPass;

    return OK;
}

sub _translateTemplate {
    my $self     = shift;
    my %args     = @_;
    my $xsltFile = $args{xsltFile};
    my $xml      = $args{xml};
    my $output;

    assert($xml);
    assert($xsltFile);

    #  !!! JPK - XMLin doesn't handle utf8 correctly if you just pass it a string.
    #  !!! It does deal with files, though, so we'll use that as a work-around.
    #
    my $tempFile = '/tmp/TranslateTemplate' . $$ . '.xml';

    open TEMPFILE, ">$tempFile" or die "ERROR - unable to open $tempFile for writing: $!";
    binmode( TEMPFILE, ":utf8" );
    print TEMPFILE "$xml\n";
    close TEMPFILE;

    my $data = XMLin($tempFile);

    unlink $tempFile;

    my $tt = new Template( { ABSOLUTE => 1, EVAL_PERL => 1 } );

    $tt->process( $xsltFile, $data, \$output );

    return $output;
}

sub _translateXML {
    my $self = shift;
    my %args = @_;
    my $xslt = $args{xslt};
    my $xml  = $args{xml};

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

    my $xsl_source = $xml_parser->parse_string($xslt);

    assert($xsl_source);

    my $xml_source = $xml_parser->parse_string($xml);
    assert($xml_source);

    my $stylesheet = $xslt_parser->parse_stylesheet($xsl_source);
    assert($stylesheet);

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

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