#!/usr/bin/perl
#use Mooix::Thing;
#use Mooix::Root;
#use Fcntl q{:flock};
run sub {
	my $this=shift;
	%_=@_;
	
	my $lock=$this->getlock(LOCK_EX);
	return unless $this->flying;
	
	# Sometime just land on the ground, other times on a perch.
	if (rand() < 0.2) {
		$this->msg("land") unless $_{quiet};
	}
	else {
		my $container=$Mooix::Root->concrete->container;
		my @objs=grep { $_ != $_{avoid} && $_->isa($container) && 
			        ! $_->closed && ! $_->hidden && $_ != $this } 
		         $this->location->contents->list;
		push @objs, $this->location;
		my $dest=$objs[rand @objs];
		if ($dest && $this->physics->move(object => $this, to => $dest,
			                          preposition => "on")) {
			$this->msg("landon") unless $_{quiet};
		}
		else {
			# Couldn't find an object to land on,
			# or land failed, so on the ground.
			$this->msg("land") unless $_{quiet};
		}
	}

	# Undo fly method.
	$this->defense($this->_origdefense);
	$this->flying(0);
	$Mooix::Root->system->init->unregister(object => $this, from => 'startup');
}
