package doxy;
use strict;
use warnings;

require 'WikiVar.pm';
require 'DoxygenSymbol.pm';

use File::Spec;
use Carp;
use JSON::XS;
use LWP::Simple ();

# URL for Doxygen content
use constant DOXY_URL => 'http://people.apache.org/~amc/ats/doc/html';
# Local file system path for symbol table
use constant SYMBOL_TABLE_PATH => 'doxy-sym.json';
# URL for externally base symbol table
use constant SYMBOL_TABLE_URL => 'http://people.apache.org/~amc/ats/doxy-sym.json';
# Flag for data loaded
our $LOADED_P = 0;
# The symbol table
our $SYMBOLS;
# Array of source files
our $FILES;

# Our WikiVar instance.
our $WV = Text::WikiVar->new
    ( KEYWORD_MARK => ':'
    , DELIMITER => '['
    , FALLBACK => sub { return $_[0]->raw_text; } # ignore undefined WikiVars
);

sub load_symbol_table {
    my $path = SYMBOL_TABLE_PATH;
    my $content;
    
    # Try to get an up to date copy.
    my $http_code = LWP::Simple::mirror(SYMBOL_TABLE_URL, $path);
    
    if (open(my $f,"<",$path)) {
        local $/ = undef;
        my $content = <$f>;
        my $data = decode_json($content);
        $SYMBOLS = $data->{symbols};
        $FILES = $data->{files};
        # Need the symbol elements to be of the right type
        while (my ($key, $value) = each %$SYMBOLS) {
            bless $value, 'DoxygenSymbol';
        }
        close $f;
    } else {
        warn "Failed to open Doxygen symbol table.\n";
    }
    $LOADED_P = 1;
}

$WV->assign('dox', sub {
    load_symbol_table unless $LOADED_P;
    
    my $args = shift;
    my $link; # output is constructed here
    my $name = $args->[1];
    my $data = $SYMBOLS->{$name};
    
    return "[Symbol $name not found]" unless $data;
    
    if (ref $data eq 'ARRAY') {
        $data = $data->[0]; # Just pick first one for now, need to handle better.
    }
    
    # Check to see if we want the source file instead.
    my $file = $FILES->[$data->src_idx];
    if ($args->{':src_file'}) {
        my $src = unmangle_file_name($file);
        $data = $SYMBOLS->{$src};
        return "[Source file $src for symbol $name not found]" unless $data;
        if (ref $data eq 'ARRAY') {
            # Really we should never encounter this - source files can't have overloads.
            $data = $data->[0];
        }
    }
    # Generate the link
    my $url = DOXY_URL . '/' . $file;
    $url .= '#' . $data->id if $data->id;
    $link = "<a href=\"$url\"";
    if ($data->arg_text) {
        $link .= ' title="'. $data->name . $data->arg_text . '"';
    } elsif ($data->text) {
        $link .= ' title="' . $data->text . '"'
    }
    $link .= '>' . $data->name . '</a>';
    return $link;
});

1;
