#!/usr/bin/perl
#use Fcntl q{:flock};
#use Mooix::Thing;
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 not 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 unlock this door.";
		}
	}
	
	if ($this->manuallock && $key && ! %keys) {
		fail "You can unlock this door without a key.";
	}
	elsif (! $this->manuallock && ! $key) {
		fail "You need a key to unlock this door.";
	}
	elsif (! $this->unlock) {
		fail "You cannot unlock the door.";
	}

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