#!/usr/bin/perl
# For builders and programmers, the edit method reads entire files, even if
# they're eg, sticky reference lists.
#use Mooix::Thing;
run sub {
	my $this=shift;
	%_=@_;
	my $object=$_{direct_object} || $this->usage("bad direct object");
	my $field=$_{field} || '';
	my $session=$_{session} || $this->usage("bad session");

	# Don't let a builder spoof a programmer that they own to call this
	# method.
	if ($_{avatar} != $this) {
	        fail "No!";
	}

	my $contents="";
	# Slurp in current value, doing inheritence. Don't do this for
	# methods, as overriding a method does not require editing it.
	my $file=$object->fieldfile($field);
	if (-e $file && (! -x $file || $file !~ m/parent\//)) {
		open (IN, $file) || fail "Cannot read $file ($!)";
		local $/ = undef;
		$contents=<IN>;
		close IN;
	}

	# See if the field can be set. This is a trifle expensive, but
	# it beats running the editor and only then finding out that your
	# hard work can't be saved.
	my ($stat, $msg) = $this->safechange(
		object => $object,
		field => $field,
		(map {( value => $_ )} split("\n", $contents, -1)),
	);

	if (! $stat) {
		fail $msg;
	}
	
	# Tell the session to start the edit. It will call edit_finish when
	# done.
	my $status = $session->edit(
		input => $contents,
		hint => $object->name." ".$field,
		id => $object->id."->".$field,
	);

	if ($status) {
		$session->write("Edit in progress.");
	}
	else {
		fail "Edit failed.";
	}
}
