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

# I'd like to use Time::Duration, but I don't haveta.
eval "use Time::Duration";
if ($@) {
	*::duration = sub { return shift()." seconds" };
}

run sub {
	my $this=shift;
	%_=@_;
	my %idletimes;
	my %avatars;
	# The owner of the session is the sessionmanager, which has a
	# complete list of logged-in sessions.
	foreach my $session ($_{session}->owner->sessions->list) {
		if ($session->avatar) {
			# Folks can log in more than once, so only display
			# them once.
			my $avatar=$session->avatar;
			if (! exists $avatars{$avatar->index}) {
				$avatars{$avatar->index}=$session->avatar;
			}
			# Current user is never idle..
			if ($avatar != $this) {
				my $idle=$session->idle;
				if (! exists $idletimes{$avatar->index} || 
				    $idle < $idletimes{$avatar->index}) {
					$idletimes{$avatar->index} = $idle;
				}
			}
		}
	}

	foreach my $avatar (values %avatars) {
		my $hostname = $avatar->lastlogin;
		my $location = $avatar->location;
		
		# Find the main room the avatar is in, ignoring subrooms,
		# like furniture and stuff.
		my $oldloc;
		while (ref $location) {
			$oldloc = $location;
			$location = $location->location;
		}
		$location = $oldloc;
		# Location can be unset if a new user is
		# just loggin in (esp guests).
		if (! ref $location) {
			$location="limbo";
		}
		# These uses of msg are a bit tricky -- the who.msg and
		# who_idle.msg of each avatar are used (to allow
		# customizability), but the message itself is delivered
		# only to the avatar who is running this verb.
		if ($idletimes{$avatar->index} > 0) {
			$this->msg('who_idle', %_,
				originator => $avatar,
				onlyto => $this,
				idletime => duration($idletimes{$avatar->index}),
				mylocation => $location,
			);
		}
		else {
			$this->msg('who', %_,
				originator => $avatar,
				onlyto => $this,
				mylocation => $location,
			);
		}
	}
}
