package Shiar_Sheet::FormRow;

use 5.014;
use warnings;
use PLP::Functions 'EscapeHTML';

our $VERSION = '1.00';

sub input {
	my ($row, $col, $attr) = @_;
	my $val = $row->{$col} // '';
	my $html = '';
	$html .= qq( $_="$attr->{$_}") for sort grep {!/^-/} keys %{$attr // {}};

	if (my $options = $attr->{-select}) {
		$options = $options->(@_) if ref $options eq 'CODE';
		$options->{$val} //= "unknown ($val)";  # preserve current
		return (
			sprintf('<select id="%s" name="%1$s">', $col),
			(map { sprintf('<option value="%s"%s>%s</option>',
				$_, $val eq $_ && ' selected', $options->{$_}
			) } sort keys %{$options}),
			'</select>',
		);
	}
	elsif ($attr->{type} eq 'textarea') {
		return (
			(map {
				sprintf('<label for="%s">%s</label>', $col, $_)
			} $attr->{-label} // ()),
			sprintf('<textarea id="%s" name="%1$s"%s>%s</textarea>',
				$col, $html, EscapeHTML($val)
			),
		);
	}
	elsif ($attr->{type} eq 'checkbox') {
		$html .= ' checked' if $val;
		return sprintf(
			join('',
				'<label>',
				'<input name="%1$s" value="0" type="hidden" />',
				'<input id="%s" name="%1$s" value="1"%s>',
				' %s</label>',
			), $col, $html, $attr->{-label}
		);
	}
	else {
		my $multiple = ref $val eq 'ARRAY' || $attr->{-multiple};
		return (
			(map {
				sprintf('<label for="%s">%s</label>', $col, $_)
			} $attr->{-label} // ()),
			$multiple ? '<span class="inline multiinput">' : (),
			(map {
				sprintf('<input name="%s" value="%s" />', $col, EscapeHTML($_))
			} ref $val eq 'ARRAY' ? @{$val} : ()),
			sprintf('<input id="%s" name="%1$s" value="%s"%s />',
				$col, $multiple ? '' : EscapeHTML($val), $html
			),
			$multiple ? '</span>' : (),
		);
	}
}

1;
