#!/usr/bin/perl
# Programmers can use the set/is command to set a field of an object to a
# reference to another object.
#use Mooix::Thing;
run sub {
	my $this=shift;
	%_=@_;
	my $object=$_{direct_object} or $this->usage("bad direct object");  
	my $field=$_{field} or $this->usage("bad field");
	my $index=$_{number} || 1; # index is 1-based
	my $val=$_{indirect_object} or $this->usage("bad indirect object");

	# Don't let a builder spoof a programmer that they own to call this
	# method.
        if ($_{avatar} != $this) {
		fail "No!"; 
	}
	
	if ($field eq 'parent') {
		# Use the reparent_verb, since it does a great deal of
		# crucial sanity checking.
		$this->exec->reparent_verb(%_);
	}
	
	# Prevent accidental overwrite of text field with reference.
	if ($object->defines($field) && ! -k $object->fieldfile($field) && 
	    ! ref $object->$field) {
		fail "That field is a string value, not a reference.";
	}
	
	my @vals=$object->$field;
	# Any index larger than the current number of values just adds to
	# the end. It wouldn't do to insert some item at position one
	# million or something..
	if ($index > @vals) {
		push @vals, $val;
	}
	else {
		$vals[$index - 1]=$val; # perl arrays are 0-based
	}
	
	eval { $object->$field(@vals) };
	if (! length $@) {
		$_{session}->write("Set.");
	}
	else {
		fail "You can't set that.";
	}
}
