#!/usr/bin/perl
#use Fcntl q{:flock};
#use Mooix::Thing;
#use Mooix::Root;
run sub ($) {
	my $this=shift;
	my $interval=$this->interval;
	foreach my $avatar ($Mooix::Root->system->sessionmanager->avatars->list) {
		next unless ref $avatar;

		# Lock object to prevent races.
		my $lock = $avatar->getlock(LOCK_EX | LOCK_NB);
		next unless $lock;
			
		my $currentloc = $avatar->location;
		next if ! $avatar->sleeping ||
			! $avatar->cleanable ||
			! $currentloc;

		# The outermost room's sleep_ok field controls things.
		my $loc=$currentloc;
		my $oldloc;
		while (ref $loc) {
			$oldloc=$loc;
			$loc=$loc->location;
		}
		next if $oldloc->sleep_ok;

		# Work out when the avatar went to sleep, based on the
		# timestamp of its sleeping field.
		my $file=$avatar->fieldfile("sleeping");
		my $sleeptime=time - (stat($file))[9]; # 9 = mtime
		if ($sleeptime > $interval / 2) {
			my $home = $avatar->home;
			my $homeok = 0;
			if (ref $home) {
				# Look at the sleep_ok field of the
				# avatar's home, or the room it's in if it
				# is in a room.
				my $h=$home;
				my $oldh;
				while (ref $h) {
					$oldh=$h;
					$h=$h->location;
				}
				
				$homeok = 1 if $oldh->sleep_ok;
			}
		
			my $dest = $homeok ? $home : $this->dormitory;
			next if $dest == $loc;

			if ($avatar->physics->move(object => $avatar, to => $dest, teleport => 1)) {
				$oldloc->msg('moveoutavatar',
					originator => $this,
					dest => $dest,
					avatar => $avatar,
				);
				$dest->msg('moveinavatar',
					originator => $this,
					location => $dest,
					avatar => $avatar,
				);
			}
		}
	}
}
