# -------------------------------------------------------------------------------------
# flo::Template::Headlines
# -------------------------------------------------------------------------------------
#
#         Author : Jean-Michel Hiver (jhiver@cisedi.com)        (c) MKDoc Holdings Ltd.
#    Description : Lets you pull headlines from other pages
#
#    <% headlines base="/news/" set="News"
#                 sort_by="Date_Created" descending="1" limit="20" %>
#
#    <ul>
#      <% loop name="News" %>
#        <li>
#          <a href="<% var name="URI" %>"><% VAR name="Title" encode_html="1" %></a>
#        </li>
#      <% end-loop %>
#    </ul>
#
# -------------------------------------------------------------------------------------
package flo::Template::Headlines;
use lib::Template::AbstractTag;
use lib::Exception;
use lib::Template;
use flo::Standard;
use lib::sql::Condition;
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_hash) = $self->parse_tag (shift @{$tokens});
    
    my $set = $token_hash->{set} or
        throw (new lib::Exception ( code => 'VARIABLE_NOT_SET',
                                    info => "$token_name should have a 'symbol' attribute" ) );
    
    my $base = $token_hash->{base} or
        throw (new lib::Exception ( code => 'NO_BASE_SPECIFIED_BASE',
                                    info => "$token_name should have a 'base' attribute" ) );
    
    my $sort_by = $token_hash->{sort_by} or
        throw (new lib::Exception ( code => 'NO_SORT_BY_SPECIFIED',
                                    info => "$token_name should have a 'sort_by' attribute" ) );
    
    my $descending = $token_hash->{descending} || 0;
    
    my $limit = $token_hash->{limit} || 20;
    
    # grabs the document descendants
    my $document_table = table ('Document');
    my $document = $document_table->get ( Full_Path => path_info );

    # builds a new condition object to perform the query
    my $condition = new lib::sql::Condition;
    $condition->add ('Full_Path', 'LIKE', $base . '_%');
    
    # performs the query and put results in the stash
    my $query = $document_table->select ( {
	cols => '*',
	where => $condition,
	sort => [ $sort_by ],
	desc => $descending,
	page => [ 1, $limit ],
    } );
    
    $lib::Template::STASH->{$set} = $query->fetch_all;
}


1;
