#!/usr/bin/perl
# Completions for builders includes mooix: completions.
#use Mooix::Thing;
#use Mooix::Root;

# Given an object, list the objects inside it, and return a list of
# "mooix:" strings that have paths relative to the passed directory.
sub mungelist {
	my $obj = shift;
	my $dir = shift;
	my @list = map {
		s/\Q$dir\E\/?// if length $dir;
		"$_/";
	} $obj->list;
	if ((grep /^mooix:\//, @list) && $obj->implements('rellist')) {
		# Get a true relative list.
		return map { "mooix:$_" } $obj->rellist;
	}
	return @list;
}

run sub {
	my $this = shift;
	%_ = @_;
	my $text = $_{text};

	my @path=grep { ref $_ } map {
		if (/^\./) {
			$_ = Mooix::Thing->get($this->id."/".$_);
		}
		elsif (/^\//) {
			$_ = Mooix::Thing->get($Mooix::Root->id.$_);
		}
		$_;
	} $this->refpath;
	
	my @ret="mooix:portfolio/";
	
	if ($text =~ m/^mooix:portfolio/i) {
		push @ret, mungelist($this->portfolio, $this->id);
	}
	elsif ($text =~ m/^mooix:(.*)/i) {
		my $path = $1;
		my $baseobj;
		if ($path =~ m/^\//) {
			# Absolute path.
			my ($basedir) = $path =~ m/(.*)\//;
			if ($baseobj = Mooix::Thing->get($basedir)) {
				@ret = mungelist($baseobj, "");
			}
		}
		else {
			# Complete mooix objecte matching the basedir of the
			# path.
			$path = "/".$1;
			my ($basedir) = $path =~ m/(.*)\//;
			foreach my $obj (@path) {
				if ($baseobj = Mooix::Thing->get($obj->id."/".$basedir)) {
					push @ret, mungelist($baseobj, $obj->id);
				}
			}
		}
	}
	else {
		# Add top-level mooix directories from path to completions.
		push @ret, map { mungelist($_, $_->id) } @path;
	}
	
	return @ret, $this->super(@_);
}
