#!/usr/bin/perl -w

# Copyright 2001-2006 The Apache Software Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

=head1 NAME

doc_viewer - A pod viewer for the local AxKit2 docs

=head1 SYNOPSIS

  <Location /docs>
  Plugin doc_viewer
  </Location>

=head1 DESCRIPTION

This plugin uses Pod::SAX to turn the local POD docs into XML for rendering in
the browser.

=cut

use Pod::SAX;
use XML::LibXML::SAX::Builder;

sub hook_xmlresponse {
    my ($self, $input) = @_;
    
    my $uri = $self->client->headers_in->request_uri();
    
    $self->log(LOGDEBUG, "request for $uri");
    
    $uri =~ s/\/docs//;
    
    # map URI to path
    if ($uri eq '/') {
        $uri = 'lib/AxKit2.pm';
    }
    elsif ($uri =~ /::/) {
        $uri =~ s/^\///;
        my $module = $uri;
        $uri = "lib/$uri" unless $uri =~ /plugins::/;
        $uri =~ s/::/\//g;
        if    (-e "${uri}.pm") { $uri .= '.pm' }
        elsif (-e "${uri}.pod") { $uri .= '.pod' }
        else {
            die "Invalid module name: $module" if $module =~ /[^\w:]/;
            chomp($uri = `perldoc -l '$module'`);
        }
        if ($uri !~ /\//) {
            return NOT_FOUND;
        }
    }
    else {
        # Ignore?
        # die "Unsupported URL: $uri";
        return NOT_FOUND;
    }
    
    my $builder = XML::LibXML::SAX::Builder->new();
    my $p = Pod::SAX->new( Handler => $builder );
    
    open(my $fh, $uri) || die "Failed to open($uri): $!";
    $p->parse_file($fh);
    
    my $doc = $builder->result();
    
    $input->dom($doc);
    
    my $out = $input->transform(XSLT('demo/xslt/main.xsl'));

    return OK, $out;
}