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

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

run sub {
	my $this = shift;
	%_=@_;
	my $session=$_{session} or $this->usage("bad session");
	my $nosleep=$_{nosleep};
	my $quiet=$_{quiet};

	# This method runs stackless, and it only allows the sessionmanager
	# to ask it to log out.
	if (! Mooix::CallStack::calledby($Mooix::Root->system->sessionmanager, 'logout')) {
		$this->croak("only the sessionmanager can call this method");
	}

        # Print logout banner. To get the duration of the login, look at the
	# creation time of the session's directory.
	my $logintime = (stat($session->id))[9]; # mtime
        $session->write("You were logged in for ". duration(time - $logintime).".")
                unless $quiet;
	
	$this->sessions->remove(object => $session);

	# If that was the last session, put them back to sleep.
	# XXX Small race here; if two sessions are logged out of
	# simulantaneously.
	# Ignore the log session, if there is one.
	my $log=$this->log;
	if (! $nosleep && ! $this->sleeping &&
	    ! (grep { $_ != $log } $this->sessions->list)) {
		$this->sleeping(1);
		# Don't display the sleep message if the avatar is
		# unconcious or dead.
		$this->msg('sleep', avatar => $this) unless $quiet || $this->hitpoints <= 0;
	}
}
