package Apache::AxKit::Pipeline::SAX;

use strict;
use vars qw/@ISA $VERSION/;
use XML::SAX::Machines qw( Pipeline );
use Apache::AxKit::Pipeline;
use XML::SAX::Writer;
use XML::LibXML::SAX;	# ParserFactory doesn't seam to load class it calls new on
use XML::SAX::ParserFactory;
use XML::LibXML::SAX::Builder;
use Apache;

@ISA = 'Apache::AxKit::Pipeline';

$VERSION = 1.0; # this fixes a CPAN.pm bug. Bah!

# use via AxAddProcessor application/sax 'XML::SAX::Base::Class'

sub new{
	my $class = shift;
	my %args = @_;
	my $self = $class->SUPER::new(@_);
	$self->{'saxprocessor'} = $args{'href'};
	return $self;
}

sub saxprocessor{
	return shift->{'saxprocessor'};
};

sub pipeline_init{
	my ($self, $r) = @_;
	
	$self->upstream()->pipeline_init( $r );

	return $self;
}


sub get_dom{
	my ($self, $r) = @_;

	my $parser = XML::SAX::ParserFactory->parser();
	# $self->href() in this case contains the sax stylesheet name.
	my $dom_builder = XML::LibXML::SAX::Builder->new();
	return $self->get_sax( $r, $parser, $dom_builder);		
}


sub get_strref{
	my ($self, $r ) = @_;
	my $str;
	my $parser = XML::SAX::ParserFactory->parser();
	
	$self->get_sax( $r, $parser, XML::SAX::Writer->new( Output => \$str) );

	return \$str;
}

sub get_sax{
	my ($self, $r, $parser, $pipeline) = @_;

	my $instance = $self->saxprocessor();
	
	if(ref($instance)) {
		$instance->set_handler(Handler => $pipeline);
	} else {
		AxKit::Debug(3, "SAX: about to load $instance");
    	AxKit::load_module($instance);
		$instance = $instance->new( Handler => $pipeline );
	}
	my $stage = $self->stage();
	AxKit::Debug(4, "SAX[$stage]: Requesting upstream sax events");
	return $self->upstream()->get_sax( $r, $parser, $instance );
}

1;


