########################################################################
# $Header: /var/local/cvsroot/4Suite/Ft/Xml/Lib/__init__.py,v 1.5 2004/08/28 21:54:15 mbrown Exp $
"""
Functions, classes, modules that support Ft.Xml (4XML, Domlette, etc.)

Copyright 2004 Fourthought, Inc. (USA).
Detailed license and copyright information: http://4suite.org/COPYRIGHT
Project home, documentation, distributions: http://4suite.org/
"""

import os
from xml.dom import Node

from Ft.Xml import XML_NAMESPACE

__all__ = ['Language']


def Language(node):
    """
    This function returns the language property of the given instance of
    xml.dom.Node, based on xml:lang attributes present on the node or
    its ancestors. If no xml:lang attribute is present, returns None.

    The language code, if any, is returned as an uppercase string.
    """
    while node:
        if node.nodeType == Node.DOCUMENT_NODE:
            break
        elif hasattr(node, 'hasAttributeNS') and node.hasAttributeNS(XML_NAMESPACE, 'lang'):
            # found an xml:lang
            value = node.getAttributeNS(XML_NAMESPACE, 'lang')
            if value:
                #Remove suffix if there is one (why?)
                #index = value.find('-')
                #if index != -1:
                #    value = value[:index]
                value = value.upper()
            # u'' -> None because XML 1.0 3rd Edition says xml:lang=""
            # undefines the language. RDF/XML Syntax (Revised) agrees.
            return value or None
        else:
            # go on to next ancestor
            node = node.nodeType == Node.ATTRIBUTE_NODE and \
                node.ownerElement or node.parentNode

    # reached a Document node without finding an xml:lang
    return None
