package GimpSite::Navgen;

use strict;
$^W = 1;

require CompoSite;
require CompoSite::Util;
require CompoSite::Navgen;

require DBI;
require Data::Dumper;
$Data::Dumper::Indent = 1;

require GimpSite;
require GimpSite::Util;

use vars qw(%Config %Navbuild);

# Read Configuration ---------------------------------------------------------

%Config = %GimpSite::Config;

# Navigation generators for different sections -------------------------------

%Navbuild = (
    dump => sub { return (undef, undef) },

    settings => sub {
        my ($fh, $args) = @_;
        my $next = &GimpSite::Util::Settings ($fh, $args);
        return ($next, undef);
    },

    links => sub { # return link topic tree
        my ($fh, $args) = @_;

        my $db = DBI->connect(@{$Config{'db'}{'links'}})
            or die "trying connect to db [$DBI::errstr]";

        my $children = NavLinks ($args->{'links_root'}, $db);

        $db->disconnect;

        return (undef, $children);
    },
);

# Links ----------------------------------------------------------------------

sub NavLinks ($$) { # recursively generate link tree
    my ($id, $db) = @_;

    my @children = ();
    $id += 0;

    my $query = <<"";
        SELECT topic_id, title, sort_order
          FROM Topics
         WHERE parent_id = $id;

    my $stmt = $db->prepare ($query)
        or die "preparing statement [$DBI::errstr]";
    my $rows = $stmt->execute
        or die "executing statement [$DBI::errstr]";

    if ($rows) {
        while (my $topic = $stmt->fetchrow_hashref) {
            my $title = $topic->{'title'};
            $title =~ s/_/ /g;
            push @children, {
                path        => $topic->{'title'},
                order       => $topic->{'sort_order'} + 0,
                tpart       => $title,
                title       => $title,
                children    => &NavLinks ($topic->{'topic_id'}, $db),
            };
        }
    }

    $stmt->finish;

    return \@children;
}

# Generate navigation data ---------------------------------------------------

sub Run {
    my $navtree = &CompoSite::Navgen::Traverse ({'path'=>''},
                                                \%Navbuild,
                                                $Config{'basedir'},
                                                {}
                                                # $Config{'default'}
                                                );

    open NAV, ">$Config{'navfile'}" or die;
    print NAV "package GimpSite::Navdata;\n";
    my $Navdump = &Data::Dumper::Dumper ($navtree);
    $Navdump =~ s/\$VAR1/\$GimpSite::Navdata::Tree/;
    print NAV $Navdump;
    print NAV "\n1; # return true\n";
    close NAV;
    return 0;
};

1;

# EOF
