package TableOfContents;

use strict;
use vars qw(@ISA
	    $BeginTemplate $EndTemplate
	    $BeginContentTemplate $EndContentTemplate);

use ObjectTemplate;
use Template;

@ISA = qw(ObjectTemplate);

attributes qw(content);

$BeginTemplate = qq(<ol>\n);
$EndTemplate = qq(</ol>\n);
$BeginContentTemplate = qq(<li><a href="\#%counter">%content</a>\n);
$EndContentTemplate = qq(</li>\n);

################################################################
sub initialize($)
{
    my $self = shift;

    $self->content([]);
    $self->SUPER::initialize;
}

sub Add($$)
{
    my ($self, $item) = @_;

    push(@{$self->content}, $item);
}

sub AsHTML($)
{
    my $self = shift;
    
    my $last_level;
    my $html;
    for (@{$self->content}){
	# complete end tag
	for (1..$_->{dec}){
	    $html .= $EndContentTemplate . $EndTemplate;
	}
	# level deeper
	for (1..$_->{inc}){
	    $html .= $BeginTemplate;
	}
	# complete content end
	unless ($_->{inc}){
	    $html .= $EndContentTemplate;
	}
	$html .= Expand($BeginContentTemplate, $_);
	$last_level = $_->{level};
    }
    $html .= $EndContentTemplate;
    for (1..$last_level-1){    # complete end tags
	$html .= $EndTemplate;
    }
    return $html;
}
1;
