#!/usr/bin/perl
# This runs stackless. That's safe because when the method is eventually
# triggered by the heartbeat, it runs with the same stack we have now, so
# all this iuseful for is delaying method invocation.
#use Mooix::Thing;
use Mooix::CallStack;
use POSIX;
run sub {
	my $this=shift;
	%_=@_;

	my $object=$_{object} || $this->croak("object required");
	delete $_{object};
	my $method=$_{method} || $this->croak("method name required");
	my $params;
	foreach (keys %_) {
		if (/^x_(.*)/) {
			$params.="\"$1\"\n";
			if (! ref $_{$_}) {
				$params.="\"$_{$_}\"\n";
			}
			else {
				$params.="$_{$_}\n";
			}
			delete $_{$_};
		}
	}

	my $id = $this->newid;
	# Have to turn the id newid returns into a plain field name.
	$id =~ s/(?:.*)\///;
	$this->$id($object);
	if (! $id) {
		die "enquing object failed!";
	}

	my $stack=Mooix::CallStack::get();
	# remove the topmost stack segment, for this method
	my $stack=$stack->nextsegment; 
	if (! $stack) {
		die "could not find callstack!";
	}
	my $stackfile="$id.stack";
	open (OUT, ">$stackfile") || die "$stackfile: $!";
	$stack->dump(OUT);
	close OUT;
	
	my $paramfile="$id.params";
	$this->$paramfile($params);

	my $infofile="$id.info";
	$this->$infofile(join("\n", %_));

	# Inform the heartbeat process that its queue has changed. If the
	# heartbeat is not running, it will be started up.
	$this->heartbeat if $this->background;
	
	return $id;
}
