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


##
# $obj->main;
# -----------
#   Includes "something" (it can be a file, a file given by a variable, or
#   a variable itself) in the current template.
#
#   <% include file="myvariable" [from_variable="1"] [reparse="0"] %>
#   <% include data="my_variable_data" [reparse="0"] %>
##
sub main
{
    my $self   = shift;
    my $result = $self->result;
    my $tokens = $self->tokens;    
    my ($token_name, $token_info) = $self->parse_tag (shift @{$tokens});

    my $data;

    # <% include file="myfile.tmpl" %>
    # <% include file="myvariable" from_variable="1" %>
    if (defined $token_info->{file})
    {
	my $file;
	if (defined $token_info->{from_variable} and $token_info->{from_variable})
	{
	    $file = $self->get ($token_info->{file});
	}
	else
	{
	    $file = $token_info->{file};
	}

	$file = $self->get_filepath ($file);
	open FP, "<$file" or
	    throw (new lib::Exception ( code => 'CANNOT_OPEN_FILE',
					info => $self ) );
	$data = join '', <FP>;
	close FP;
    }

    # <% include data="my_variable_data" %>
    elsif (defined $token_info->{data})
    {
	$data = $self->get ($token_info->{file});
    }
    else
    {
	throw (new lib::Exception ( code => 'UNVALID_INCLUDE_TAG',
				    info => $self ) );
    }

    # <% include ... reparse="1" %> (default)
    # <% include ... reparse="0" %> (does not re-parse the included file)
    $token_info->{reparse} = 1 unless (exists $token_info->{reparse});
    if ($token_info->{reparse})
    {
	my $tmpl = $self->{class}->new ( data => $data, hash => $self->{hash} );
	push @{$result}, $tmpl->parse;
    }
    else
    {
	push (@{$result}, $data);
    }
}


sub get_filepath
{
    my $self = shift;
    return shift;
}


1;

