# -------------------------------------------------------------------------------------
# lib::Template::BalancedTag
# -------------------------------------------------------------------------------------
#
#    Author   : Jean-Michel Hiver                         (c) Jean-Michel Hiver, 2001.
#    Synopsis : Provides the parse method for any tag
#               that is balanced, such as <% loop %>.
#
# -------------------------------------------------------------------------------------
package lib::Template::AbstractBalancedTag;
use lib::Template::AbstractTag;
use lib::Exception;
use lib::Template;
use strict;
use vars qw /@ISA/;
@ISA = qw /lib::Template::AbstractTag/;


##
# $obj->parse;
# ------------
#   Returns two elements: the tag info. and the tag contents.
#   alters $tokens, which is an array ref on remaining tokens.
##
sub parse
{
    my $self   = shift;
    my $tokens = shift;
    
    my $first_token  = shift (@{$tokens});
    my ($first_token_name, $first_token_info) = $self->parse_tag ($first_token);
        
    my $balance = 1;
    my $inner_data = "";
    
    while ($balance > 0)
    {
	(@{$tokens} > 0) or
	    throw (new lib::Exception ( code => uc ($first_token_name) . '_TAG_' . uc ($first_token_info->{name}) . '_NOT_CLOSED',
					info => $self ) );
	
	my $token = shift (@{$tokens});
	if ($self->is_tag ($token))
	{
	    my ($token_name, $token_info) = $self->parse_tag ($token);
	    if ($token_name eq $first_token_name)
	    {
		$balance++;
		$inner_data .= $token;
	    }
	    elsif ($token_name eq 'end-' . $first_token_name)
	    {
		$balance--;
		$inner_data .= $token unless ($balance == 0);
	    }
	    else
	    {
		$inner_data .= $token;
	    }
	}
	else
	{
	    $inner_data .= $token;
	}
    }

    return ($first_token_info, $inner_data);
}


1;





