# Scrape the Doxygen output to get a symbol table
# This is a stand alone script to be run against the Doxygen output to
# generate a symbol table. That table is loaded during a documentation
# build. It should be stored in an HTTP acccessible location and the
# build script tweaked to know that location so it can update its local
# copy as needed.

use strict;
use JSON qw(-convert_blessed_universally);
use File::Basename;

require 'DoxygenSymbol.pm';

our %SYMBOLS; # Symbol table, name -> DoxygenSymbol
our @FILES; # Array of files.

use constant DOXYGEN_BASE_DIR => '/sys/cygwin/home/amc/ats/doc/html';

sub obtain_sym {
    my ($table, $key, $src_idx) = @_;
    my $zret = $table->{$key};
    $zret = $table->{$key} = DoxygenSymbol->new(id => $key, src_idx => $src_idx) unless $zret;
    return $zret;
}

sub load_doxy_file {
    my $zret = 1;
    my ($src_idx) = @_;
    my $path = $FILES[$src_idx];
    my %items; # temp hash keyed by ID
    if (open(my $f,"<",$path)) {
        # Gather the pieces of the method data together.
        while (<$f>) {
            my $sym = undef;
            if (m/class="mdescRight">([^<]*)<.*href="#([^"]*)"/) {
                my $text = $1;
                $text =~ m/(\S+(?:\s+\S+)*)/;
                $text = $1;
                $sym = obtain_sym(\%items, $2, $src_idx);
                $sym->text($text);
            } elsif (m/doxytag: member="([^"]*)".*ref="([^"]*)".*args="([^"]*)"/) {
                $sym = obtain_sym(\%items, $2, $src_idx);
                $sym->name($1);
                $sym->arg_text($3);
            }
        }
        
        # Put the source file in as a symbol
        my $name = doxy::unmangle_file_name(basename($path));
        if ($name =~  m/[.](?:cc|h|hpp)$/) {
            $SYMBOLS{$name} = DoxygenSymbol->new(name => $name, src_idx => $src_idx, text => 'source file');
        }

        # Load the actual symbols in to the symbol table
        while (my ($key, $value) = each %items) {
            my $name = $value->name;
            $name  =~ s/^[[:alnum:]]+[.](?:h|cc|hpp):://; # strip file name as leading namespace
            $value->name($name);
            
            my $sym = $SYMBOLS{$name};
            if (not $sym) {
                $SYMBOLS{$name} = $value;
            } elsif (ref $sym) {
                push(@$sym, $value);
            } else {
                $SYMBOLS{$name} = [ $sym, $value ];
            }
        }
        close $f;
    } else {
        $zret = 0;
    }
    return $zret;
}

sub load_sym_file {
    
}

chdir(DOXYGEN_BASE_DIR);
for (glob('*.html')) {
    push(@FILES, $_);
}
for (my $idx = 0 ; $idx < scalar(@FILES) ; ++$idx) {
    load_doxy_file($idx);
}

if (open(my $f,">",'/tmp/doxy-sym.json')) {
    print $f to_json({files => \@FILES , symbols => \%SYMBOLS}, { allow_blessed => 1, convert_blessed => 1, indent => 1 });
}
exit 0;
