#!/usr/bin/perl
package XmlFormatter; 

use strict;
use XML::LibXML;

our $FC_BEG = 1;  # begin of subtree (current node descends) - in
our $FC_CTN = 2;  # continue with next sibling element - in / out: data of found element 
our $FC_END = 3;  # subtree completion (current node ascends); no data - out

sub new {
	my $self = { 
		xml => undef,            # whole document
		docNode => undef,        # root node
		currentNode => undef,
		currentParents => () };
	
	bless $self;
	return $self;
}

sub initResult {
	my $self = shift;
	$self->{'xml'} = new XML::LibXML::Document;
}
sub formatElement {
	my $self = shift;
	my $form_ctl = shift;
	my $elem = shift;   # optional
	my $value = shift;  # optional
	my %attrs = %_;     # optional

	if ($form_ctl == $FC_END) {
		die "cannot go up without valid root node." unless defined($self->{'docNode'});
		die "Hier passt der pop nicht.";
		#$self->{'currentNode'} = pop $self->{'currentParents'};
		return;
	}
	
	die "parameter elem required for node creation" unless defined($elem);
	my $elemNode = $self->{'xml'}->createElement($elem);

	if (defined($value)) {
		my $textNode = $self->{'xml'}->createTextNode($value);
		$elemNode->addChild($textNode);
	}

	while (my ($attr_key, $attr_val) = each (%attrs)) {
		my $attr = $self->{'xml'}->createAttribute($attr_key, $attr_val);
		$elemNode->appendChild($attr);
	}
	
	$self->currentNode->appendChild($elemNode);

	if ($form_ctl == $FC_BEG) {
		die "Hier passt der push nicht.";
		#push $self->{'currentParents'}, $self->{'currentNode'};
		$self->{'currentNode'} = $elemNode;
	}
}
sub finish {
	;
}
	
sub	printIt {
	my $self = shift; 
	return $self->{'xml'}->toString();
}

1;
