########################################################################
# $Header: /var/local/cvsroot/4Suite/Ft/Xml/Xslt/Exslt/Common.py,v 1.12 2005/04/06 23:05:48 jkloth Exp $
"""
EXSLT 2.0 - Common (http://www.exslt.org/exsl/index.html)

Copyright 2005 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.Lib import boolean, Uri
from Ft.Xml.XPath import Conversions
from Ft.Xml.Xslt import XsltElement, OutputParameters
from Ft.Xml.Xslt import ContentInfo, AttributeInfo
from Ft.Xml.Xslt import XsltRuntimeException, Error
from Ft.Xml.Xslt.Exslt.MessageSource import Error as ExsltError

EXSL_COMMON_NS = "http://exslt.org/common"

def NodeSet(context, obj):
    """
    The purpose of the exsl:node-set function is to return a node-set from a
    result tree fragment. If the argument is a node-set already, it is simply
    returned as is. If the argument to exsl:node-set is not a node-set or a
    result tree fragment, then it is converted to a string as by the string()
    function, and the function returns a node-set consisting of a single text
    node with that string value.

    The exsl:node-set function does not have side-effects: the result tree
    fragment used as an argument is still available as a result tree fragment
    after it is passed as an argument to exsl:node-set. 
    """
    if isinstance(obj, list):
        return obj
    elif getattr(obj, 'nodeType', None) == Node.DOCUMENT_NODE:
        return [obj]
    else:
        s = Conversions.StringValue(obj)
        return [context.node.rootNode.createTextNode(s)]


def ObjectType(context, obj):
    """
    The exsl:object-type function returns a string giving the type of the
    object passed as the argument. The possible object types are: 'string',
    'number', 'boolean', 'node-set', 'RTF' or 'external'.
    """
    if type(obj) is type([]):
        return u'node-set'
    elif type(obj) is type(u''):
        return u'string'
    elif type(obj) in [type(1), type(2.3), type(4L)]:
        return u'number'
    elif type(obj) is type(boolean.true):
        return u'boolean'
    elif getattr(obj, 'nodeType', None) == Node.DOCUMENT_NODE:
        return u'RTF'
    else:
        return u'external'


class DocumentElement(XsltElement):
    """
    For full specification, see:
    http://www.exslt.org/exsl/elements/document/index.html
    """

    content = ContentInfo.Template
    legalAttrs = {
        'href' : AttributeInfo.UriReferenceAvt(required=1),
        'method' : AttributeInfo.QNameAvt(),
        'version' : AttributeInfo.NMTokenAvt(),
        'encoding' : AttributeInfo.StringAvt(),
        'omit-xml-declaration' : AttributeInfo.YesNoAvt(),
        'standalone' : AttributeInfo.YesNoAvt(),
        'doctype-public' : AttributeInfo.StringAvt(),
        'doctype-system' : AttributeInfo.StringAvt(),
        'cdata-section-elements' : AttributeInfo.QNamesAvt(),
        'indent' : AttributeInfo.YesNoAvt(),
        'media-type' : AttributeInfo.StringAvt(),
        }

    def __init__(self, root, namespaceUri, localName, baseUri):
        XsltElement.__init__(self, root, namespaceUri, localName, baseUri)
        self._output_parameters = OutputParameters.OutputParameters()
        return

    def instantiate(self, context, processor):
        context.processorNss = self.namespaces

        # this uses attributes directly from self
        self._output_parameters.avtParse(self, context)
        href = self._href.evaluate(context)

        #Use the main input source for relative URI rather than the main
        #"output source"

        uri = processor._documentInputSource._normalize(href)
        path = Uri.UriToOsPath(uri)
        try:
            stream = open(path, 'w')
        except IOError:
            dir = os.path.split(path)[0]
            #Should we also check base path writability with os.W_OK?
            if not os.access(dir, os.F_OK):
                os.makedirs(dir)
                stream = open(path, 'w')
            else:
                raise

        processor.addHandler(self._output_parameters, stream)
        try:
            for child in self.children:
                child.instantiate(context, processor)
        finally:
            processor.removeHandler()
            stream.close()

        return


ExtNamespaces = {
    EXSL_COMMON_NS : 'exsl',
    }

ExtFunctions = {
    (EXSL_COMMON_NS, 'node-set'): NodeSet,
    (EXSL_COMMON_NS, 'object-type'): ObjectType,
    }

ExtElements = {
    (EXSL_COMMON_NS, 'document'): DocumentElement,
    }
