# -------------------------------------------------------------------------------------
# flo::Template::Split
# -------------------------------------------------------------------------------------
#
#    Author   : Jean-Michel Hiver                               (c) Jean-Michel Hiver.
#    Synopsis : Provides the implementation for the
#               <% split name="myloop" cols="3" set="my_splitted_loop" %>
#
# -------------------------------------------------------------------------------------
package lib::Template::Split;
use lib::Template::AbstractTag;
use lib::Exception;
use lib::Template;
use strict;
use vars qw /@ISA/;
@ISA = qw /lib::Template::AbstractTag/;


##
# $obj->main ($result, $tokens);
# ------------------------------
#   Splits some array.
##
sub main
{
    my $self = shift;
    my $result = $self->result;
    my $tokens = $self->tokens;    
    my ($token_name, $token_info) = $self->parse_tag (shift @{$tokens});
    
    # the name of the array to split
    my $var_name_from = $token_info->{name} || $token_info->{in} or
	throw (new lib::Exception (code => "NO_SYMBOL_SET",
				   info => $self ) );
    
    # the name where to set the new structure
    my $var_name_to   = $token_info->{set}  || $token_info->{out} or
	throw (new lib::Exception (code => "NO_SYMBOL_SET",
				   info => $self ) );
    
    # the number of columns we wish to have
    my $size = $token_info->{size} || $token_info->{cols} or
	throw (new lib::Exception (code => "NO_SYMBOL_SET",
				   info => $self ) );
    
    # grabs the structure to split
    my $array = $self->get ($var_name_from);
    
    # splits the structure into @res
    my @res = ();
    my $array_ref;
    for (my $i=0; $i < @{$array}; $i++)
    {
	my $mod = $i % $size;
	unless ($mod)
	{
	    $array_ref = [ map { {} } 1..$size ];
	    push @res, { Cols => $array_ref };
	}
	$array_ref->[$mod] = $array->[$i];
    }
    
    # sets @res where specified
    $lib::Template::STASH->{$var_name_to} = \@res;
}


1;

