package Celaenito::Template::Plugin::Hidden;
use strict;
use warnings;
use HTML::Entities;
use base 'Template::Plugin';

sub new {
    my $class = shift;
    my $context = shift;

    return sub {
	my @hiddens;
    
	if (@_ == 1) {
	    my $ref = shift;

	    if (not defined $ref or not length $ref) {
		# ignore this
	    }
	    elsif (ref($ref) eq 'ARRAY') {
		# Hidden([[a => 1], [b => 2], ...])
		@hiddens = map {
		    if (ref ne 'ARRAY') {
			die "not an array";
		    } elsif (@$_ != 2) {
			die "not a pair";
		    } else {
			$_;
		    }
		} @$ref;
	    } elsif (ref($ref) eq 'HASH') {
		# Hidden({a => 1, b => [2, 3, ...], ...})
		@hiddens = map {
		    my ($key, $val) = ($_, $ref->{$_});
		
		    if (ref($val) eq '') {
			[$key => $val];
		    } elsif (ref($val) eq 'ARRAY') {
			map {
			    [$key => $_];
			} @$val;
		    } else {
			die "neither SCALAR nor ARRAY";
		    }
		} keys %$ref;
	    } else {
		die "neither ARRAY nor HASH";
	    }
	} elsif (@_ % 2 == 0) {
	    # Hidden(a => 1, b => 2, ...)
	    for (my $i = 0; $i < @_; $i += 2) {
		push @hiddens, [$_[$i] => $_[$i + 1]];
	    }
	} else {
	    die "invalid call";
	}

	join("\n", map {
	    sprintf(
		'<input type="hidden" name="%s" value="%s" />',
		encode_entities($_->[0], '<>&"'),
		encode_entities($_->[1], '<>&"'));
	} @hiddens);
    };
}

1;
