#!/usr/bin/perl
#use Mooix::Thing;

sub fillout {
	my $template=shift;
	my $adjective=shift;
	$template=~s/\$adjective/$adjective/g;
	return $template;
}

run sub {
	my $this = shift;
	%_=@_;
	return unless $this->enabled;
	
	# Find a adjective for the new guest. A pointer is kept to the previous
	# adjective assigned; we'll find the first unused adjective after it
	# (looping  back to the start of the list if necessary). This ensures
	# that all the adjectives get equal exposure.
	my @adjectives=$this->adjectives;
	my %usedadjectives=map { $_->adjective => 1 } $this->guests->list;
	my $prev=$this->_prev || $adjectives[0];
	my $i; # index of prev
	for ($i=0; $i < @adjectives && $adjectives[$i] ne $prev; $i++) { }
	foreach my $adjective (@adjectives[($i+1)..$#adjectives, 0..($i-1)]) {
		if (! $usedadjectives{$adjective}) {
			# Found a free one.
			$this->_prev($adjective);

			# Create the guest.
			my $id = $this->guests->newid(mkdir => 1, hint => $adjective);
			my $name = fillout($this->name_template, ucfirst $adjective);
			my $guest=$this->template->new(id => $id, owner => $this,
				name => fillout($this->name_template, ucfirst $adjective));
			$guest->adjective($guest->adjective, $adjective);
			$guest->description(fillout($this->description_template, $adjective));
			$guest->alias($guest->alias, $adjective);
			
			return $guest;
		}
	}

	if ($_{session}) {
		$_{session}->write("Sorry, too many guests are logged in. Try again later.");
		# This could be a bad problem, so I'll syslog it in the
		# hope that logs are checked.
		require Sys::Syslog;
		Sys::Syslog::setlogsock('unix');
		Sys::Syslog::openlog('mooix', '', 'user');
		Sys::Syslog::syslog('warning', "All guest users are in use.");
	}
	
	return "";
}
