#!/usr/bin/perl -w

sub init {
    my $self = shift;
    
    $self->register_config('WikiDBRoot', sub { $self->set_cfg('WikiDBRoot', @_) });
    $self->register_config('WikiDB', sub { $self->set_cfg('WikiDB', @_) });
    $self->register_config('WikiDefaultPage', sub { $self->set_cfg('WikiDefaultPage', @_) });
    $self->register_config('WikiEmailTo', sub { $self->set_cfg('WikiEmailTo', @_) });
}

sub set_cfg {
    my ($self, $key, $conf, $value) = @_;
    
    $key = $self->plugin_name . "::$key";
    $conf->notes($key, $value);
}

sub get_cfg {
    my ($self, $key) = @_;
    $key = $self->plugin_name . "::$key";
    $self->config->notes($key);
}

sub hook_body_data {
    my ($self, $bref) = @_;
    
    my $client = $self->client;
    my $remaining = $client->notes('wiki::bytes_remaining');
    if (!$remaining) {
        $remaining = $client->headers_in->header('Content-Length');
        return DONE unless $remaining;
    }
    
    my $data = $client->notes('wiki::body_data') || '';
    $data .= $$bref;
    $remaining -= length($data);
    $client->notes('wiki::body_data', $data);
    
    if (!$remaining) {
        # parse $data
        my $ct = $client->headers_in->header('Content-Type');
        if ($ct eq 'application/x-www-form-urlencoded') {
            for my $param (split(/[&;]/, $data)) {
                my ($key, $value) = split(/=/, $param, 2);
                next unless defined $key && defined $value;
                $key   =~ tr/+/ /;
                $key   =~ s/%([0-9a-fA-F]{2})/chr(hex($1))/eg;
                $value =~ tr/+/ /;
                $value =~ s/%([0-9a-fA-F]{2})/chr(hex($1))/eg;
                
                $client->headers_in->add_param($key, $value);
            }
        }
        else {
            die "Unhandled form type: $ct";
        }
        return DONE;
    }
    
    return DECLINED;
}

sub hook_xmlresponse {
    my ($self, $input) = @_;
    
    $self->log(LOGDEBUG, "Delivering Wiki");
    
    return DECLINED if $self->client->headers_in->filename !~ /(view|edit|attachments)$/;
    
    for (qw(WikiDBRoot WikiDB WikiDefaultPage WikiEmailTo)) {
        $self->client->notes($_, $self->get_cfg($_));
    }
    
    my $file = $self->client->headers_in->filename;
    $file =~ s/.*\///;
    
    $AxKit2::Processor::DumpIntermediate = 1;
    
    my $out = $input->transform(
        XSP()
          => 
            XSLT('/Users/matt/Perl/AxKit2-XSP-Wiki/webstuff/wiki.xsl',
                 'action'      => $self->client->param('action') || $file,
                 'request.uri' => $self->client->headers_in->uri,
                 )
    );
    
    return OK, $out;
}
