#!/usr/bin/perl
#use Fcntl q{:flock};
#use Mooix::Thing;
#use Mooix::Verb;
run sub {
	my $this = shift;
	%_=@_;
	my $avatar = $_{avatar};
	my $key = $_{indirect_object};
	my %keys = map { $_ => 1} $this->key;
	
	# Lock both this side and the otherside's locked field, to prevent
	# modification races.
	require $this->fieldfile("getlock.pl");
	my @locks=getduallock($this, LOCK_EX, "locked");
	
	if ($this->locked) {
		fail "It is already locked.";
	}

	if (! $this->manuallock) {
		if (! $key && %keys) {
			# Try to find a valid key in the avatar's
			# direct inventory.
			foreach my $obj ($avatar->contents->list) {
				my $keyval = $obj->key;
				next unless length $keyval;
				# Always set $key, that way if the avatar
				# has a key but it's the wrong one, they'll
				# get a message about that.
				$key=$obj;
				if (exists $keys{$keyval}) {
					last;
				}
			}
		}
		
		if ($key) {
			# See if the given key is valid.
			if (! exists $keys{$key->key}) {
				$this->msg('badkey', key => $key, %_);
				fail;
			}
			if ($key->location != $avatar) {
				fail "You're not holding that key.";
			}
		}
		else {
			fail "You need a key to lock this door.";
		}
	}
	
	if ($this->manuallock && $key && ! %keys) {
		fail "You can lock this door without a key.";
	}
	elsif (! $this->manuallock && ! $key) {
		# See if the other side of the door can be manually locked,
		# if it is open. If so, let's let the avatar reach around
		# and lock that side..
		if (! $this->closed && ref $this->otherside &&
                      $this->otherside->manuallock &&
		      $this->otherside->lock) {
		      	$this->msg('lock_otherside', %_)
		}
		else {
			fail "You need a key to lock this door.";
		}
	}
	elsif (! $this->lock) {
		fail "You cannot lock the door.";
	}

	$this->msg('lock', %_);
}
