#!/usr/bin/perl
# TODO: differentiate between methods and fields. Tricky, since they can
# change back and forth in inheritance..
# It would be _great_ if I could list the parameters of a method, 
# accumulating them from each .inf file in parents, so if a method
# is overridden and a parameter added, it gets added to the list.
use warnings;
use strict;
use Cwd q{realpath};
#use Mooix::Thing;
run sub {
	my $this=shift;
	%_=@_;

	# Hash of arrays.
	my %entries;

	# Holds the keys of %entries in the order they were seen.
	my @entries;

	# Holds fields, and if the values are true, the fields are documented.
	my %documented;

	my $obj=$this;
	while ($obj) {
		opendir (COLLECT, $obj->id);
		foreach my $field (sort readdir COLLECT) {
			if ($_{field}) {
				next unless $field eq $_{field} or
				            $field eq $_{field}.'.inf';
			}
			if ($field =~ /(.*)\.inf$/) {
				my $base=$1;
				$documented{$base} = 1;
				if (! exists $entries{$base}) {
					$entries{$base} = [];
					push @entries, $base;
				}
				my $line;
				# Realpath used just for prettiness.
				$line .= "  [From mooix:".realpath($obj->id)."]\n\n"
					if $this != $obj;
				$line .= "  ".join("\n  ", $obj->$field);
				push @{$entries{$base}}, $line;
			}
			elsif (! exists $documented{$field}) {
				$documented{$field} = 0;
			}
		}
		closedir COLLECT;
		
		# Opendir won't work, since it typically means opening a
		# symlink, and mood enforces O_NOFOLLOW. So change to the dir,
		# and get a new object. Mooix::Thing doesn't really like
		# changing dirs all around, but as long as we throw away
		# our old object, and get a new one, it won't get confused.
		if (chdir("parent")) {
			$obj = Mooix::Thing->get(".");
		}
		else {
			last;
		}
	}

	if (@entries) {
		foreach my $entry ('design', grep { $_ ne 'design' } @entries) {
			if (exists $entries{$entry}) {
				print "$entry\n\n";
		
				foreach my $inf (@{$entries{$entry}}) {
					print "$inf\n\n";
				}
			}
		}
	}

	# Ignore a lot of stuff that doesn't need usage docs.
	my @undoc=grep { ! $documented{$_} && $_ !~ /(^\.|~$|^CVS$|^\.svn$|\.lnk|\.msg|_verb|\.cmd|\.hlp$|\.c$|^Makefile$)/ } keys %documented;
	if (@undoc) {
		print join ("\n\t", "Undocumented:", @undoc), "\n";
	}

	if (! @entries and ! @undoc) {
		print "No such field or method.";
	}
	
	return;
}
