package Template::Plugin::Sitemap;

use strict;
use XML::Simple;
use Template::Plugin;
use base qw( Template::Plugin );

sub new {
    my ($class, $context, $config) = @_;
    my $dir;
    my $file = $config->{ file } 
        || return $class->error("no file");

    if ($file =~ m[ (.*?) / ([^/]+) $ ]x) {
        $dir = $1;
    }
    else {
        $dir = '.';
    }

    my $self = bless {
        _context => $context,
        file => $file,
        dir  => $dir,
        url  => $config->{ url } || '',
    }, $class;

    $self->{ map } = $self->load_xml_sitemap($file)
        || return;

    return $self;
}


sub throw {
    my $self = shift;
    $self->{ _context }->throw( sitemap => join('', @_) );
}


sub load_xml_sitemap {
    my ($self, $file, $path) = @_;
    $file = "$self->{ dir }/$file" unless $file =~ m[^/];

    my $map;
#    $self->debug("loading $file\n");

    eval {
        $map = XMLin($file, KeyAttr => [ ], ForceArray => ['menu', 'page']);
    };
    $self->throw("$file: ", $@) if $@;

    return $self->extend($map, $path);
}


sub extend {
    my ($self, $map, $path) = @_;
#    $self->debug("extending map $map->{ name }\n");

    return unless ref $map->{ page } eq 'ARRAY';

    my $items = $map->{ items } = $map->{ page };
    my $pages = $map->{ page  } = { };

    foreach my $item (@$items) {
        $pages->{ $item->{ id } } = $item;

        $item->{ path } = $path ? "$path/$item->{ id }" : $item->{ id };

        # load any page specified in config option
        if ($item->{ config }) {
            my $subpage = $self->load_xml_sitemap($item->{ config }, 
                                                  $item->{ path }) || return;
            @$item{ keys %$subpage } = values %$subpage;
        }
        $item->{ title } = $item->{ name  } unless defined $item->{ title };
        $item->{ name  } = $item->{ title } unless defined $item->{ name  };
        $item->{ subs  } = $item->{ page  } ? 1 : 0;
        $item->{ file  } = $item->{ subs  }
                  ? "$item->{ path }/index.html" 
                  : "$item->{ path }.html";
        $item->{ url   } = "$self->{ url }/$item->{ file }";

#       $self->debug(" - extending page $item->{ name }\n");

        $self->extend($item, $item->{ path }) || return
            if ref $item->{ page } eq 'ARRAY';
    }

    return $map;
}

1;
