# -------------------------------------------------------------------------------------
# lib::Template::Loop
# -------------------------------------------------------------------------------------
#
#    Author   : Jean-Michel Hiver                         (c) Jean-Michel Hiver, 2001.
#    Synopsis : Provides the implementation for the
#    <% loop ... %> tag
# -------------------------------------------------------------------------------------
package lib::Template::Loop;
use lib::Template::AbstractBalancedTag;
use lib::Exception;
use lib::Template;
use strict;
use vars qw /@ISA/;
@ISA = qw /lib::Template::AbstractBalancedTag/;


##
# $obj->main;
# -----------
#   Loops thru a value, which has to be an array reference.
#   Some special variables are added:
#   
#   __count__, __is_first__, __is_last__,
#   __is_inner__, __even__, __odd__
##
sub main
{
    my $self = shift;
    
    my $result = $self->result;
    my $tokens = $self->tokens;
    
    # parses $tokens to extract the loop data
    my ($info, $data) = $self->parse ($tokens);

    # which variable do we want to test ?
    my $varname = $info->{name};
    my $value   = $self->get ($varname);
    
    # if $value is not an ARRAY reference, then let's
    # complain about it
    (ref $value and (ref $value eq 'ARRAY')) or
	throw (new lib::Exception ( code => 'NOT_AN_ARRAY_REF',
				    info => "$varname is not an array reference" ) );
    
    my $count = 1;
    foreach my $hash (@{$value})
    {
	(ref $hash and ($hash =~ /HASH\(/)) or
	    throw (new lib::Exception ( code => 'NOT_A_HASH_REF',
					info => $self ) );
	$hash->{__count__} = $count;
	$hash->{__is_first__} = ($count == 1);
	$hash->{__is_last__} = ($count == @{$value});
	$hash->{__is_inner__} = (not $hash->{__is_first__} and not $hash->{__is_last__});
	$hash->{__even__} = ($count % 2 == 0);
	$hash->{__odd__}  = not $hash->{__even__};
	
	my $stack_hash = $self->stack_hash ( $self->{hash}, $hash );
	bless $stack_hash, ref $hash unless (ref $hash eq 'HASH');
	my $tmpl = $self->{class}->new ( data => $data, hash => $stack_hash );
	push @{$result}, $tmpl->parse;
	$count++;
    }
}


1;



