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

my @visicontents;

# This sub handles a look for objects that have a particular releationship
# to the furniture.
sub look_prep {
	my $this=shift;
	my $preplist=shift;
	my %okpreps = map { $_ => 1 } @{shift()};
	%_=@_;
	my $avatar=$_{avatar};
	
	my ($message)=$preplist=~m/(.*)_/;
	
	# Show standing on scale the same as just being on it. This is a
	# special case.
	if ($message eq 'on') {
		map { $okpreps{$_} = 1 } $this->stand_prepositions;
	}
	
	# If its closed, and not transparent, then skip some lists.
	if ($this->closed && ! $this->transparent) {
		return if grep { $_ eq $preplist } $this->closedpreps;
	}
	
	# Find objects that match the preposition list.
	my @contents;
	foreach my $obj (@visicontents) {
		# Only look at objects that have the right leading
		# preposition.
		next unless $okpreps{($obj->preposition)[0]};
		push @contents, $obj;
	}
	
	$this->msg("look_$message", %_,
		contents => @contents ? $avatar->prettylist(@contents) : 'nothing',
		are => (@contents > 1 || ($contents[0] == $avatar && @contents == 1)) ? 'are' : 'is',
	);
}

run sub {
	my $this=shift;
	%_=@_;
	my $preposition=lc($_{do_preposition});
	$avatar=$_{avatar};
		
	foreach ($this->contents->list) {
		if (! $_->hidden) {
			push @visicontents, $_;
		}
		elsif ($_->defines("detail")) {
			$_{details}.=" ".$_->detail;
		}
	}
	
	if (! $_{direct_object}) {
		# If no direct object was specified (the user just
		# did a "look", then they must be in/on/whatever this
		# furniture. Display a message to that effect, and then
		# let them look at the enclosing room.
		if ($avatar->location != $this) {
			exit Mooix::Verb::SKIP;
		}
		
		$this->location->look_verb(@_) if $this->location;
		$this->msg('occupied', %_, preposition => ($avatar->preposition)[0]);
	}
	elsif (length $preposition && $preposition ne 'at') {
		# If certian prepositions are specified, what is seen depends
		# on the preposition. Looking underneath the object could
		# return one set, while looking in it might return another.
		my $ok=0;
		foreach my $preplist ($this->preplists) {
			my @list=$this->$preplist;
			if (grep { $_ eq $preposition } @list) {
				look_prep($this, $preplist, \@list, %_);
				$ok=1;
				last;
			}
		}
		if (! $ok) {
			fail "Nothing there.";
		}
	}
	else {
		# If no preposition was specified, do a regular look, and 
		# use the visible ones.
		$this->msg('look', %_);
		foreach my $preplist ($this->visiblepreps) {
			look_prep($this, $preplist, [$this->$preplist], %_);
		}
	}

	if ($this->closed) {
		$this->msg('closed', %_);
	}
}
