#!/usr/bin/perl
#use Mooix::Thing;
use Mooix::CallStack;
run sub {
	my $this=shift;
	%_=@_;
	my $session=$_{session} || $this->croak("bad session");
	my @contents = map { split("\n", $_, -1) } $_{value};
	my $id=$_{id};

	# Check that the session in question is one of the avatar's.
	if ((! grep { $_ == $session } $this->sessions->list) ||
	    $session->avatar != $this) {
		$this->croak("bad session");
	}
	# Only that session and the avatar can be on the callstack.
	# Anything else would be a spoof attempt.
	my $stack=Mooix::CallStack->get || $this->croak("bad callstack");
	while ($stack) {
		if ($stack->index != $this->index &&
		    $stack->index != $session->index) {
			$this->croak("bad object on callstack");
		}
		$stack=$stack->next;
	}
	
	my ($objid, $field) = $id =~ /(.*)->(.*)/;
	my $object=$this->get($objid);
	if (! ref $object || ! length $field) {
		$session->write("Ignoring request to save edit to unknown id: $id");
		return;
	}
	my $prettyid=$object->prettyname."'s ".$field;
	
	my ($stat, $msg) = $this->safechange(
		object => $object,
		field => $field,
		(map {( value => $_ )} @contents),
	);
	if (! $stat) {
		$session->write("Unable to save changes to ${prettyid}: $msg.");
		return
	}
	else {
		$session->write("Saved changes to ${prettyid}.");
		return 1;
	}
}
