#!/usr/bin/python
# -*- coding: utf-8 -*-

# Copyright 2012 Harri Pitkänen (hatapitk@iki.fi)
# Script for automating the build of grammar checker help web pages.
# This script should be run in the directory where the resulting
# help pages are written.

# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

import codecs
import sys
from os import access, F_OK
from os import waitpid
from shutil import copyfile, move
from datetime import datetime
import voikkoutils
from xml.dom.minidom import parse

def printCommonHeader(helpFile, pageTitle):
	helpFile.write(u"<!DOCTYPE html>")
	helpFile.write(u"<html lang='fi'><head><title>Voikko &mdash; %s</title>" % pageTitle)
	helpFile.write(u"<meta http-equiv='content-type' content='text/html; charset=utf-8' />")
	helpFile.write(u"<link rel='stylesheet' type='text/css' href='../../stylesheets/styles.css' /></head><body>")

def printHelpContent(helpFile, errorCode, errorTitle, errorContent):
	helpFile.write(u"<h1>%s</h1>" % errorTitle)
	helpFile.write(u"<p>")
	helpFile.write(errorContent)
	helpFile.write(u"</p>")

def printCommonFooter(helpFile):
	helpFile.write(u"<div style='clear:both;'></div>")
	helpFile.write(u"</body></html>")


# === Main program ===

xmlData = parse(voikkoutils.get_preference("corevoikko") + "/libvoikko/data/gchelp.xml")

indexFile = codecs.open("index.html", "w", "UTF-8")
printCommonHeader(indexFile, u"Kielioppivirheiden selitykset")
indexFile.write(u"<h1>Kielioppivirheiden selitykset</h1><ul>")

for errorElement in xmlData.documentElement.getElementsByTagName("error"):
	errorCode = errorElement.getAttribute("code")
	errorTitle = errorElement.getElementsByTagName("description")[0].firstChild.wholeText;
	errorContent = errorElement.getElementsByTagName("help")[0].firstChild.wholeText;
	helpFile = codecs.open(errorCode + ".html", "w", "UTF-8")
	printCommonHeader(helpFile, u"kielioppivirheen selitys")
	printHelpContent(helpFile, errorCode, errorTitle, errorContent)
	printCommonFooter(helpFile)
	helpFile.close()
	indexFile.write(u"<li><a href='%s.html'>%s</a></li>" % (errorCode, errorTitle))

indexFile.write("</ul>")
printCommonFooter(indexFile)
indexFile.close()

