#!/usr/bin/python

import sys, time, xml.dom.minidom

# templates

MANUAL="SOPE Dynamic Element Reference"
COPYRIGHT="SKYRIX Software AG"

HEADER=""".TH %(element)s %(section)i "%(month)s %(year)s" "SOPE" "%(manual)s"
.\\" DO NOT EDIT: this file got autogenerated using woapi2man from:
.\\"   %(file)s
.\\" 
.\\" Copyright (C) %(year)s %(copy)s. All rights reserved.
.\\" ====================================================================
.\\"
.\\" Copyright (C) %(year)s %(copy)s. All rights reserved.
.\\"
.\\" Check the COPYING file for further information.
.\\"
.\\" Created with the help of:
.\\"   http://www.schweikhardt.net/man_page_howto.html
.\\"
"""

BUGS="""
.SH BUGS
SOPE related bugs are collected in the OpenGroupware.org Bugzilla:
  http://bugzilla.opengroupware.org/
"""

AUTHOR="""
.SH AUTHOR
The SOPE community <developer at opengroupware.org>.
"""

SEEALSO="""
.SH SEE ALSO
.BR sope-ngobjweb-defaults
"""

FOOTER="\n"

PASSTHROUGHTEXT="This binding is a pass-through binding.\n"

# Note: texts may not start with a single quote: '
DEFAULTSTEXT="Kind: %s\n"
KINDTOTEXT={
    'Page Names': "The value of '%(name)s' will be used to lookup a WOComponent page.\n",
    'Actions':    "The '%(name)s' binding is evaluated as an action (a method which returns a WOComponent or other WOActionResults object).\n",
    'Resources':  "The value of '%(name)s' refers to a resource which will be looked up using the WOResourceManager.\n",
    'YES/NO':     "The value of '%(name)s' will be evaluated in a boolean context.\n",
    'Frameworks': "The value of '%(name)s' must be the name of a framework or bundle to be used for resource lookups.\n",

#    'Direct Actions': "The value of '%(name)s' refers to the name of a direct action method.\n",
#    'Direct Action Classes': "The value of '%(name)s' refers to the name of a direct action class.\n"
}

# processing

class DOMToManPage:

    def __init__(self, _path, _dom):
        self.path = _path
        self.dom  = _dom
        self.out  = sys.stdout
    
    def clear(self):
        self.path = None
        self.dom.unlink()
        self.dom = None
    
    def printManPageHeader(self, woroot):
        self.out.write(HEADER % {
            'file':    self.path,
            'element': woroot.getAttribute('class'),
            'section': 3,
            'month':   time.strftime("%B"),
            'year':    time.strftime("%Y"),
            'manual':  MANUAL,
            'copy':    COPYRIGHT
            })
    
    def printManPageName(self, woroot):
        self.out.write("\n.SH NAME\n%s\n" % woroot.getAttribute('class'))
    
    def printManPageBugs(self, woroot):
        self.out.write(BUGS)

    def printManPageAuthor(self, woroot):
        self.out.write(AUTHOR)

    def printManPageSeeAlso(self, woroot):
        self.out.write(SEEALSO)
    
    def printManPageFooter(self, woroot):
        self.out.write(FOOTER)
    
    def printSynopsis(self, woroot):
        self.out.write("\n.SH SYNOPSIS\n")
        self.out.write(".B %s\n" % woroot.getAttribute('class'))
        self.out.write("{")
        for binding in woroot.getElementsByTagName("binding"):
            self.out.write(" %s; " % binding.getAttribute('name'))
        self.out.write("}\n")

    def escapeText(self, text):
        if text[0] == "'":
            return "\\" + text
        return text
    
    def getTextForBindingKind(self, binding, kind):
        if kind is None:   return
        if len(kind) == 0: return
        if KINDTOTEXT.has_key(kind):
            info = { 'kind': kind,
                     'name': binding.getAttribute('name') }
            s = KINDTOTEXT[kind]
            s = s % info
            return s
        
        return DEFAULTSTEXT % ( kind, )
    
    def printBindings(self, woroot):
        self.out.write("\n.SH BINDINGS\n")
        for binding in woroot.getElementsByTagName("binding"):
            self.out.write(".IP %s\n" % binding.getAttribute('name'))
            s = binding.getAttribute('passthrough')
            if (s and s == 'YES'):
                self.out.write(PASSTHROUGHTEXT)
            s = binding.getAttribute('defaults')
            if (s and len(s) > 0):
                self.out.write(self.getTextForBindingKind(binding, s))
    
    def printValidation(self, woroot):
        vals = woroot.getElementsByTagName("validation")
        if (vals.length == 0): return
        self.out.write("\n.SH VALIDATION\n")
        for val in vals:
            m = val.getAttribute('message')
            if not m: continue
            if len(m) == 0: continue
            self.out.write("%s\n" % self.escapeText(m.capitalize()))
    
    def processDOM(self):
        woroot = self.dom.getElementsByTagName("wo")[0]
        self.printManPageHeader(woroot)
        self.printManPageName(woroot)
        
        self.printSynopsis(woroot)
        self.printValidation(woroot)
        self.printBindings(woroot)
        
        self.printManPageBugs(woroot)
        self.printManPageAuthor(woroot)
        self.printManPageSeeAlso(woroot)
        self.printManPageFooter(woroot)

    def processBinding(self, element):
        print "  check binding", element.getAttribute('name')

    def processValidation(self, element):
        print "  check validation:", element.getAttribute('message')

    def processWOTag(self, element):
        print "check element class", element.getAttribute('class')
        
        for binding in dom.getElementsByTagName("binding"):
            self.processBinding(binding)
        for subelem in dom.getElementsByTagName("validation"):
            self.processValidation(subelem)
    
#class DOMToManPage

# main function

path = sys.argv[1]
try:
  dom = xml.dom.minidom.parse(path)
except IOError, e:
        sys.stderr.write("%s:0: %s\n" % ( path, e ))
except xml.parsers.expat.ExpatError, xmle:
        sys.stderr.write("%s:%i: %s\n" % ( path, xmle.lineno, xmle ))
if dom is None:
    sys.exit(1)

cpu = DOMToManPage(path, dom)
cpu.processDOM()
cpu.clear()
