# -------------------------------------------------------------------------------------
# flo::Template::Text2Html
# -------------------------------------------------------------------------------------
#
#    Author   : Jean-Michel Hiver                               (c) MKDoc Holdings Ltd.
#
# -------------------------------------------------------------------------------------
package flo::Template::Text2Html;
use lib::Template::AbstractTag;
use lib::Exception;
use lib::Template;
use lib::util::Text2Html;
use flo::Standard;
use strict;
use vars qw /@ISA/;
@ISA = qw /lib::Template::AbstractTag/;


sub main
{
    my $self = shift;
    my $result = $self->result;
    my $tokens = $self->tokens;    
    my ($token_name, $token_info) = $self->parse_tag (shift @{$tokens});
    
    my $varname = $token_info->{name} || $token_info->{in} or
	throw (new lib::Exception ( code => 'VARIABLE_NOT_SET',
				    info => "$token_name should have a 'name' attribute" ) );
    
    my $value = $self->get ($varname);
    push @{$result}, $self->html ($value);
}


sub html
{
    my $self = shift;
    my $data = shift;
    my @data = split /\n/, $data;
    my @out  = ('');
    foreach my $line (@data)
    {
        chomp ($line);
        if ($line !~ /^\s*$/x) { $out[$#out] .= $line . "\n" }
        else
        {
            $out[$#out] eq '' and next;
            push @out , '';
        }
    }
    
    my $res = join "</p>\n<p>\n", map { text2html ($_) } @out;
    return $self->_make_links ($res);
}


sub _make_links
{
    my $self = shift;
    my $res  = shift;
    while (my ($text_link) = $res =~ /(\S*\s+\{.*?\})/si)
    {
        my ($path, $title) = $text_link =~ /(\S*)\s+\{(.*?)\}/si;
        my $url = undef;
        my $cgi = lib::cgi::CGI->get;
        my $cgix = $cgi->new;
        if ($path =~ /^\//)
        {
            $cgix->path_info ($path);
            $url = $cgix->self_url;
        }
        elsif ($path !~ /^[a-z]+:.+/i)
        {
            my @current = split /\//, path_info;
            my @next = split /\//, $path;
            while (my $next = shift (@next))
            {
                $next eq '.' and next;
                $next eq '..' and pop (@current) and next;
                push @current, $next;
            }
            $cgix->path_info (join '/', @current);
            $url = $cgix->self_url;
        }
        else { $url = $path }

        my $q_text_link = quotemeta ($text_link);
        my $h_link = "<a href=\"$url\">$title</a>";
        $res =~ s/$q_text_link/$h_link/;
    }
    
    return "<p>\n" . $res . "</p>";
}


1;

