#!/usr/bin/perl
# Builders can use the set/is command to set a field of an object to a
# reference to another object. This goes through safechange.
#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");

	# Sntispoofing.
        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
	}
	
        my ($stat, $msg)=$this->safechange(
		object => $object,
		field => $field,
		(map { (value => $_ ) } @vals),
	);

        if (! $stat) {
		fail $msg;
	}
	else {
		$_{session}->write("Set.");
	}
}
