package HTML::Form::Simple;

use strict;
use warnings;

use XML::Quote;

our $VERSION = '1.00';


sub new {
	bless {}, $_[0];
}

sub quote {
	my $self = shift;
	return XML::Quote::xml_quote_min($_[0]);
}

sub tag {
	my ($self, $tag, $attr) = @_;

	# strip empty if it shouldn't be
	defined $attr->{$_} and $attr->{$_} eq '' and delete $attr->{$_}
		for qw(id type);

	my $return = '<' . $tag;

	# add booleans
	delete $attr->{$_} and $return .= ' '.$_
		for qw(disabled readonly);

	$return .= sprintf ' %s="%s"', $_, $self->quote($attr->{$_})
		for sort grep { defined $attr->{$_} } keys %$attr;

	return $return . '>';
}


sub start {
	my ($self, $attr) = @_;

	return $self->tag(form => $attr);
}

sub stop {
	return '</form>';
}


sub submit {
	my ($self, $value, $attr) = @_;

	if (ref $value eq 'HASH') {
		$attr = $value;
	}
	else {
		$attr ||= {};
		$attr->{value} = $value;
	}

	$attr->{type} = 'submit' unless defined $attr->{type};

	return $self->tag(input => $attr);
}

sub hidden {
	my ($self, $name, $value) = @_;

	#TODO: $attr

	return $self->tag(input => {type => 'hidden', name => $name, value => $value});
}

sub input {
	my ($self, $name, $value, $attr) = @_;

	if (ref $name eq 'HASH') {
		# only attributes provided (first argument)
		$attr = $name;
	}
	elsif (ref $value eq 'HASH') {
		# name shorthand (attributes in value parameter)
		$attr = $value;
		$attr->{name} = $name;
	}
	else {
		# name and value shorthands (all vars keep their assigned values)
		$attr ||= {};
		$attr->{name} = $name;
		$attr->{value} = $value;
	}

	$attr->{id}   = $attr->{name} unless defined $attr->{id};
	$attr->{type} = 'text' unless defined $attr->{type} or defined $attr->{rows};
	$value = delete $attr->{value} if defined $attr->{rows};

	return defined $attr->{rows} ? sprintf(
		'%s%s</textarea>',
		$self->tag(textarea => $attr),
		$self->quote(defined $value ? $value : '')
	) : $self->tag(input => $attr);
}

sub select {
	my ($self, $name, $rows, $value, $attr) = @_;

	if (ref $value eq 'HASH') {
		$attr = $value;
	}
	else {
		$attr ||= {};
	}
	$attr->{name} = $name;

	return $self->tag(select => $attr) . join('',
		map { $self->tag(option => (ref $_ ? $_ : {value => $_})) } @$rows
	) . '</select>';
}

1;

=head1 NAME

HTML::Form::Simple

=head1 SYNOPSIS

	my $input = HTML::Form::Simple->new;
	say $input->start; # <form>
	printf "<label>%s: %s</label>\n", @$_ for (
		[ 'Your Name' => $input->text(username => 'Mr. Default') ],
		[ Colour => $input->select(
			favcolour => [qw(Blue Green Red)], 'Green'
		) ],
	);
	say $input->stop; # </form>

