#!/usr/bin/perl -w # -*- mode: perl -*-


require 5.002;

use strict;

use lib "../../..";
use XML::Writer;
use XML::Handler::EasyTree::Visitor;

package XML::Handler::EasyTree::WriteVisitor;
use vars qw(@ISA @EXPORT_OK);


require Exporter;
@ISA=qw(Exporter
	XML::Handler::EasyTree::Visitor);
@EXPORT_OK= qw(new
	       start_visit
	       end_visit
	      );

sub new(){
  my $class = shift;
  my $self = {};
  bless $self, $class;
  $self->initialize(@_);
  return $self;
}

sub initialize{
  my$self=shift;

  my%in_parameters=(@_);

  my $lOutHandle= $in_parameters{outstream}    || $in_parameters{OUTPUT};
  my $lDocType=   $in_parameters{doctype}      || $in_parameters{DOCTYPE};
  my $lEncoding=  $in_parameters{encoding}     || $in_parameters{ENCODING} || "UTF-8";
  my $lStandalone=$in_parameters{standalone}   || $in_parameters{STANDALONE} || "yes";

  if(defined $lOutHandle){
    $self->{writer}=XML::Writer->new( OUTPUT => $lOutHandle,
				      #DATA_MODE => 1,
				      #DATA_INDENT => 2
				      );
  }else{
    $self->{writer}=XML::Writer->new();
  }
  $self->{writer}->xmlDecl("$lEncoding","$lStandalone");

  if($lDocType){
    $self->{writer}->doctype(@$lDocType);
  }
}

#########################################
#
# start_visit
#
# prints the start (i.e. opening tag) or the text contained in the node
#
# PARAMETERS: The start_visit function takes a tree node (i.e. a hash reference)
# as parameter. 
#
# RETURNS:    1: if the traversal should go deeper,
#             0: otherwise
#
sub start_visit( $ ){
  my $self=shift;
  my $lRoot=shift;

  if($lRoot->{type} eq 'e'){
    $self->{writer}->startTag($lRoot->{name},(%{$lRoot->{attrib}}));
    $self->{writer}->characters("\n");
  }elsif($lRoot->{type} eq 't'){
    $self->{writer}->characters($lRoot->{content});
  }
  return 1;# visit more!
}
#########################################
#
# end_visit
#
# prints the end tag
#
# PARAMETERS: The end_visit function takes a tree node (i.e. a hash reference)
#    as parameter. The parameter is provided by CGIFTLink::traverse 
#
# RETURNS:    nothing
#
sub end_visit( $ ){
  my $self=shift;
  my $lRoot=shift;
  if($lRoot->{type} eq 'e'){
    $self->{writer}->endTag($lRoot->{name});
  }
}
