use XML::SAX::Base;
use XML::NamespaceSupport;

package W3C::XML::HandlerStack;
@W3C::XML::HandlerStack::ISA = qw(XML::SAX::Base);

sub new {
    my ($proto, @rest) = @_;
    my $class = ref($proto) || $proto;
    my $self = {HandlerStack => [], 
		NSHelper => XML::NamespaceSupport->new({xmlns => 1}), 
		schemaParser => undef, 
		@rest};
    bless ($self, $class);
    return $self;
}

sub set_handler {
    my ($self, $handler) = @_;
    if ($self->{ParseOptions}{'Handler'} != $handler) {
	# Clear SAX callback cache.
	foreach my $method (keys %{$self->{Methods}}) {
	    delete $self->{Methods}{$method};
	}
	$self->{ParseOptions}{'Handler'} = $handler;
    }
}

sub get_namespace_helper {
    my ($self) = @_;
    return $self->{NSHelper};
}

sub start_prefix_mapping {
    my ($self, $mapping) = @_;
    $self->{NSHelper}->declare_prefix($mapping->{Prefix},
				      $mapping->{NamespaceURI});
    if (my $relay = $self->{-relay}) {
	$relay->addNamespace($mapping->{Prefix},
			     $mapping->{NamespaceURI}, undef);
    }
}

sub end_prefix_mapping {
    my ($self, $mapping) = @_;
    $self->{NSHelper}->undeclare_prefix($mapping->{Prefix});
}

sub start_element {
    my ($self, $data) = @_;
    push (@{$self->{HandlerStack}}, $self->{ParseOptions}{'Handler'});
    $self->SUPER::start_element($data);
}

sub end_element {
    my ($self, $data) = @_;
    $self->set_handler(pop (@{$self->{HandlerStack}}));
    $self->SUPER::end_element($data);
}

1;

