# -------------------------------------------------------------------------------------
# flo::Template::DocumentList
# -------------------------------------------------------------------------------------
#
#       Author : Jean-Michel Hiver (jhiver@cisedi.com).
#    Copyright : (c) MKDoc Holdings Ltd, 2000.
# 
#      Unauthorized modification, use, reuse, distribution or redistribution
#      of this module is stricly forbidden.
#
#      <% document_list set="DocList" depth="2" %>
#
# -------------------------------------------------------------------------------------
package flo::Template::DocumentList;
use lib::Template::AbstractTag;
use lib::Exception;
use lib::Template;
use flo::Standard;
use lib::sql::Table;
use lib::cgi::CGI;
use Data::Dumper;
use strict;
use vars qw /@ISA/;
@ISA = qw /lib::Template::AbstractTag/;


##
# $obj->main;
# -----------
#   Parses and displays the value of a variable.
#   <% sticker name="my.nifty.sticker" %>
##
sub main
{
    my $self   = shift;
    my $result = $self->result;
    my $tokens = $self->tokens;
    my ($token_name, $token_hash) = $self->parse_tag (shift @{$tokens});

    # $symbol that we are going to use for that document list.
    my $symbol = $token_hash->{set} or
	throw (new lib::Exception ( code => 'VARIABLE_NOT_SET',
				    info => "$token_name should have a 'symbol' attribute" ) );
    
    # maximum depth for the document listing.
    my $max_depth = $token_hash->{depth} || 1;
    
    # gets the document which we are currently dealing with.
    my $document_table = table ('Document');
    my $document = $document_table->get ( Full_Path => path_info ) or
	throw (new lib::Exception ( code => 'CANNOT_GET_DOCUMENT',
				    info => cgi ) );

    $lib::Template::STASH->{$symbol} = $self->_retrieve_by_depth ($document, $max_depth);
}


sub _retrieve_by_depth
{
    my $self = shift;
    my $document = shift;
    my $max_depth = shift or return [];
    my $current_depth = shift || 1;
    my @result = ();
    
    # select all child of $document by alphabetical order on Full_Path
    my $document_table = table ('Document');
    my $query = $document_table->select ( cols  => [ qw /ID Full_Path Title Description Lang/ ],
					  where => { Parent_ID => $document->{ID} },
					  sort  => [ qw /Full_Path/ ] );
    
    my $cgix = cgi->new;
    while (my $h = $query->next)
    {
	$h->{Depth} = [ map { {} } 1..$current_depth ];
	$cgix->path_info ($h->{Full_Path});
	$h->{URI} = $cgix->self_url;
	push @result, $h;
	push @result, @{$self->_retrieve_by_depth ($document, $max_depth - 1, $current_depth + 1)};
    }
    
    return \@result;
}


1;


