#!/usr/pkg/bin/perl

########################################################################
## Copyright by Franz-Benjamin Mocnik, 2010
##
## Dieses Skript erstellt aus den Daten der Datei $xml_filename eine html-Datei $cache_filename.
## Diese wird wiederum mittels Template Toolkit in das Internetangebot eingebunden.
##
## used modules:
## XML::DOM
########################################################################

use strict;

###### settings
my $xml_filename = '../data/bms.xml';
my $cache_filename = '../cache/bms.html';
my $icon_pdf = '../files/img/iconPdf_small.gif';
my $bms_download_path = '../../downloads/bms/';
my $bms_download_path_html = '../downloads/bms/';

###### prepare xml dom parser
use XML::DOM;
my $parser = XML::DOM::Parser->new();
my $doc = $parser->parsefile($xml_filename);

###### toolbox
## get the value of a text subNode
sub getText {
	my $item = $_[0]->getElementsByTagName($_[1])->item(0);
	if ($item eq undef) {
		return '';
	} else {
		if ($item->getFirstChild eq undef) {
			return '';
		} else {
			return $item->getFirstChild->getNodeValue();
		}
	}
}

## get the value of a text subNode
sub getAttribute {
	return $_[0]->getAttribute($_[1]);
}

## get books
sub getBooks {
	return $doc->getElementsByTagName('book');
}

###### build cache

my $count = 0;
my $previousYear;
# open file
open(FILE, ">$cache_filename");
foreach my $book (getBooks()) {
	# parse xml data
	my $number = getAttribute($book, 'number');
	my $author = getText($book, 'author');
	my $title = getText($book, 'title');
	my $year = getText($book, 'year');
	# save year
	unless ($year eq $previousYear) {
		print FILE "<tr class=\"bibBMSYear\">\n\t<th colspan=\"4\">$year</th>\n</tr>\n";
		$count = 0;
	}
	$previousYear = $year;
	# save book
	my $a = '';
	if (-e "${bms_download_path}BMS-$number.pdf") {
		$a = "<a href=\"${bms_download_path_html}BMS-$number.pdf\"><img src=\"$icon_pdf\" alt=\"PDF Icon\"/></a>";
	}
	my $classOdd = '';
	if ($count % 2) {
		$classOdd = 'class="odd" ';
	}
	$count++;
	print FILE "<tr ${classOdd}id=\"bibBMS-$number\">\n";
	print FILE "\t<td class=\"bibBMSDownload\">$a</td>\n";
	print FILE "\t<td class=\"bibBMSNumber\"><t><de>Nr. $number</de><en>No. $number</en></t></td>\n";
	print FILE "\t<td class=\"bibBMSAuthor\">$author</td>\n";
	print FILE "\t<td class=\"bibBMSTitle\">$title</td>\n";
	print FILE "</tr>\n";
}
# close file
close(FILE);

$doc->dispose();

exit(0);
