#!/usr/bin/env python

import sys, os, os.path, re, string
from distutils.filelist import FileList
from distutils.errors import *
from util import *
import distutils.cmd
import glob

def show_formats ():
	"""Print all possible values for the 'formats' option (used by
	the "--help-formats" command-line option).
	"""
	print 'fd'
	from distutils.fancy_getopt import FancyGetopt
	formats=['dvi', 'txt', 'pdf', 'ps', 'html', 'htmlhelp']
	formats.sort()
#	pretty_printer = FancyGetopt(formats)
#	pretty_printer.print_help(
#		"List of available source distribution formats:")


class build_doc(distutils.cmd.Command):

	description = '"build" documentation.'

	user_options = [
		('force', 'f', "forcibly build everything (ignore file timestamps)"),
		('formats=', None, 'Formats for documentation'),
		]

	boolean_options = ['force']

	help_options = [
		('help-formats', None,
		 "list available distribution formats", show_formats),
		]


	def initialize_options (self):
		self.force = None
		self.formats = None


	def finalize_options (self):
		self.set_undefined_options('build', ('force', 'force'))
		self.ensure_string_list('formats')
		if self.formats is None:
			self.formats = ['html']
		if 'all' in self.formats:
			self.formats = ['html', 'onehtml', 'htmlhelp', 'ps', 'pdf', 'dvi']


	def saxon(self, xsl, output, params):
		if params.has_key('base_dir'):
			for f in glob.glob(params['base_dir'] + '*'):
				os.remove(f)
		saxon_cmd = ['java', '-cp', self.saxon_jars, 'com.icl.saxon.StyleSheet']
		if output is not None:
			saxon_cmd.extend(['-o', output])
		saxon_cmd.extend([self.source, xsl])
		for key, value in params.items():
			saxon_cmd.append('%s=%s' % (string.replace(key, '_', '.'), value))
		self.spawn(saxon_cmd)


	def hhc(self):
		try:
			self.spawn(['hhc', 'manual.hhp'])
		except DistutilsExecError, e:
			print e
		self.copy_file('manual.chm', '../../../OpenGL/doc')


	def pdflatex(self):
		for i in range(3):
			self.spawn(['pdflatex', '&pdfxmltex', 'manual.xml'])


	def latex(self):
		for i in range(3):
			self.spawn(['latex', '&xmltex', 'manual.xml'])


	def run (self):
		if not os.environ.has_key('SAXON_HOME') or not os.environ.has_key('DOCBOOK_XSL_HOME'):
			self.warn("Can't generate docs because SAXON_HOME or DOCBOOK_XSL_HOME environment variable is not set.  Will just use existing docs.")
			return
		
		self.saxon_jars = string.join([os.path.join(os.environ['SAXON_HOME'], 'saxon.jar'),
								  os.path.join(os.environ['DOCBOOK_XSL_HOME'], 'extensions', 'saxon643.jar')],
								 os.pathsep)
		self.source = os.path.abspath(os.path.join('OpenGL', 'doc', 'manual.xml'))

		fo_xsl = os.path.join(os.environ['DOCBOOK_XSL_HOME'], 'fo', 'docbook.xsl')
		one_html_xsl = os.path.join(os.environ['DOCBOOK_XSL_HOME'], 'html', 'docbook.xsl')
		html_xsl = os.path.join(os.environ['DOCBOOK_XSL_HOME'], 'html', 'chunk.xsl')
		htmlhelp_xsl = os.path.join(os.environ['DOCBOOK_XSL_HOME'], 'htmlhelp', 'htmlhelp.xsl')

		options = {'saxon.extensions':1,
				   'chunk.first.sections':1,
				   'generate.index':1,
				   'passivetex.extensions':1,
				   'suppress.navigation':0,
				   'use.extensions':1,
				   'use.id.as.filename':1,
				   'alignment':'left',
				   'htmlhelp.chm':'manual.chm',
				   'htmlhelp.hhp':'manual.hhp',
				   'htmlhelp.hhp.tail':'..\\..\\..\\OpenGL\\doc\\style.css',
				   'html.stylesheet':'style.css'}

		for format in self.formats:
			if format == 'html':
				html_options = {'base_dir':os.path.join('OpenGL', 'doc', 'html', '')}
				html_options.update(options)
				self.make_file(['OpenGL/doc/manual.xml'],
							   'OpenGL/doc/html/index.html',
							   self.saxon,
							   (html_xsl,
								None,
								html_options),
							   exec_msg = 'Generating HTML documentation',
							   skip_msg = "HTML documentation doesn't need updating")
				self.copy_file('OpenGL/doc/style.css', 'OpenGL/doc/html')
			elif format == 'onehtml':
				self.make_file(['OpenGL/doc/manual.xml'],
							   'OpenGL/doc/manual.html',
							   self.saxon,
							   (one_html_xsl,
								os.path.join('OpenGL', 'doc', 'manual.html'),
								options),
							   exec_msg = 'Generating HTML documentation',
							   skip_msg = "HTML documentation doesn't need updating")
			elif format == 'htmlhelp':
				self.mkpath('build/doc/htmlhelp')
				os.chdir(os.path.join('build', 'doc', 'htmlhelp'))
				self.make_file([self.source],
							   'index.html',
							   self.saxon,
							   (htmlhelp_xsl,
								None,
								options),
							   exec_msg = 'Generating HTML file for HTML Help documentation',
							   skip_msg = "HTML files for HTML Help documentation don't need updating")
				self.make_file(['manual.hhp'],
							   'manual.chm',
							   self.hhc,
							   (),
							   exec_msg = 'Generating CHM file for HTML Help documentation',
							   skip_msg = "CHM file for HTML Help documentation doesn't need updating")
				os.chdir(os.path.join(os.pardir, os.pardir, os.pardir))
			else:
				self.mkpath('build/doc/fo')
				self.make_file(['OpenGL/doc/manual.xml'],
							   'build/doc/fo/manual.xml',
							   self.saxon,
							   (fo_xsl,
								os.path.join('build', 'doc', 'fo', 'manual.xml'),
								options),
							   exec_msg = 'Generating FO file',
							   skip_msg = "FO file doesn't need updating")
				os.chdir(os.path.join('build', 'doc', 'fo'))

				if format == 'pdf':
					self.make_file([],
								   'pdfxmltex.fmt',
								   self.spawn,
								   (['pdftex', '-ini', '&pdflatex', 'pdfxmltex.ini'],),
								   exec_msg = 'Generating FMT file',
								   skip_msg = "FMT file doesn't need updating")
					self.make_file(['manual.xml'],
								   'manual.pdf',
								   self.pdflatex,
								   (),
								   exec_msg = 'Generating PDF file',
								   skip_msg = "PDF file doesn't need updating")
				else:
					self.make_file([],
								   'xmltex.fmt',
								   self.spawn,
								   (['tex', '-ini', '&latex', 'xmltex.ini'],),
								   exec_msg = 'Generating FMT file',
								   skip_msg = "FMT file doesn't need updating")
					self.make_file(['manual.xml'],
								   'manual.dvi',
								   self.latex,
								   (),
								   exec_msg = 'Generating DVI file',
								   skip_msg = "DVI file doesn't need updating")

				if format == 'ps':
					self.make_file(['manual.dvi'],
								   'manual.ps',
								   self.spawn,
								   (['dvips', '-o', 'manual.ps', 'manual.dvi'],),
								   exec_msg = 'Generating PS file',
								   skip_msg = "PS file doesn't need updating")

				os.chdir(os.path.join(os.pardir, os.pardir, os.pardir))
				self.copy_file('build/doc/fo/manual.' + format, 'OpenGL/doc')
				