##############################################################################
# 
# Zope Public License (ZPL) Version 1.0
# -------------------------------------
# 
# Copyright (c) Digital Creations.  All rights reserved.
# 
# This license has been certified as Open Source(tm).
# 
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
# 
# 1. Redistributions in source code must retain the above copyright
#    notice, this list of conditions, and the following disclaimer.
# 
# 2. Redistributions in binary form must reproduce the above copyright
#    notice, this list of conditions, and the following disclaimer in
#    the documentation and/or other materials provided with the
#    distribution.
# 
# 3. Digital Creations requests that attribution be given to Zope
#    in any manner possible. Zope includes a "Powered by Zope"
#    button that is installed by default. While it is not a license
#    violation to remove this button, it is requested that the
#    attribution remain. A significant investment has been put
#    into Zope, and this effort will continue if the Zope community
#    continues to grow. This is one way to assure that growth.
# 
# 4. All advertising materials and documentation mentioning
#    features derived from or use of this software must display
#    the following acknowledgement:
# 
#      "This product includes software developed by Digital Creations
#      for use in the Z Object Publishing Environment
#      (http://www.zope.org/)."
# 
#    In the event that the product being advertised includes an
#    intact Zope distribution (with copyright and license included)
#    then this clause is waived.
# 
# 5. Names associated with Zope or Digital Creations must not be used to
#    endorse or promote products derived from this software without
#    prior written permission from Digital Creations.
# 
# 6. Modified redistributions of any form whatsoever must retain
#    the following acknowledgment:
# 
#      "This product includes software developed by Digital Creations
#      for use in the Z Object Publishing Environment
#      (http://www.zope.org/)."
# 
#    Intact (re-)distributions of any official Zope release do not
#    require an external acknowledgement.
# 
# 7. Modifications are encouraged but must be packaged separately as
#    patches to official Zope releases.  Distributions that do not
#    clearly separate the patches from the original work must be clearly
#    labeled as unofficial distributions.  Modifications which do not
#    carry the name Zope may be packaged in any form, as long as they
#    conform to all of the clauses above.
# 
# 
# Disclaimer
# 
#   THIS SOFTWARE IS PROVIDED BY DIGITAL CREATIONS ``AS IS'' AND ANY
#   EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
#   IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
#   PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL DIGITAL CREATIONS OR ITS
#   CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
#   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
#   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
#   USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
#   ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
#   OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
#   OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
#   SUCH DAMAGE.
# 
# 
# This software consists of contributions made by Digital Creations and
# many individuals on behalf of Digital Creations.  Specific
# attributions are listed in the accompanying credits file.
# 
##############################################################################
"""
A simple example implementation of DOMProxy.

Provide a class to implement wrapDOMObj(), mix that and the DOMProxy proxy
classes, and add whatever you want to make it interesting.
"""

import DOMProxy
import Acquisition

class TransPubWrapper:
    """
    Mixin class to go alongside DOMProxy classes.  Provides the wrapDOMObj
    function to create TransPubNode classes.  This is what makes TransPubNodes
    transient - we never re-use proxies, but create new ones when we need them.
    """
    
    # In the future we may want to return different proxy types based
    # on non-DOM node types, such as DB/nonDB.  Probably map
    # the same way that the DOM classes will map.
    def wrapDOMObj(self, node):
        """
        Return the appropriate manageable class wrapped around the Node.
        We never create Nodes ourselves, only wrap existing ones.
        Wrapped node can be single DOM object, a non-DOM object, or a
        container that contains only non-DOM objects - DOM objects in
        containters aren't wrapped.
        """
        from xml.dom import Node
        import types
        if node == None:
            return None
        elif isinstance(node, types.InstanceType) \
             and node.__class__.__name__ == "ChildNodeList": # XXX impl detail
            return TransPubNodeList(node)
        elif isinstance(node, types.InstanceType) \
             and node.__class__.__name__ == "AttributeMap": # XXX impl detail
            return TransPubNamedNodeMap(node)
        elif not hasattr(node, "nodeType"):
            return node                     # not DOM, don't wrap.
        elif node.nodeType == Node.ELEMENT_NODE:
            return TransPubElement(node)
        elif node.nodeType == Node.ATTRIBUTE_NODE:
            return TransPubAttr(node)
        elif node.nodeType == Node.TEXT_NODE:
            return TransPubText(node)
        elif node.nodeType == Node.CDATA_SECTION_NODE:
            return TransPubCDATASection(node)
        elif node.nodeType == Node.ENTITY_REFERENCE_NODE:
            return TransPubEntityReference(node)
        elif node.nodeType == Node.ENTITY_NODE:
            return TransPubEntity(node)
        elif node.nodeType == Node.PROCESSING_INSTRUCTION_NODE:
            return TransPubProcessingInstruction(node)
        elif node.nodeType == Node.COMMENT_NODE:
            return TransPubComment(node)
        elif node.nodeType == Node.DOCUMENT_NODE:
            return TransPubDocument(node)
        elif node.nodeType == Node.DOCUMENT_TYPE_NODE:
            return TransPubDocumentType(node)
        elif node.nodeType == Node.DOCUMENT_FRAGMENT_NODE:
            return TransPubDocumentFragment(node)
        elif node.nodeType == Node.NOTATION_NODE:
            return TransPubNotation(node)
        else:
            raise TypeError


_TRANS_PUB_DOM_PROXY_FEATURES = (
    ("org.zope.dom.acquisition", None),
    ("org.zope.dom.acquisition", "1.0"),
    )

class TransPubDOMImplementation(DOMProxy.DOMImplementationProxy):
    """
    A DOMImplementation proxy that implements createDocument to produce
    TransPubDocument instances.
    """

    def hasFeature(self, feature, version):
        feature = string.lower(feature)
        if (feature, version) in _TRANS_PUB_DOM_PROXY_FEATURES:
            return 1
        return self._domimplementation.hasFeature(feature, version)
    
    def createDocument(self, namespaceURI, qualifiedName, docType=None):
        DOMDocument = self._createDOMDocument(namespaceURI,
                                              qualifiedName, docType)
        return TransPubDocument(DOMDocument.aq_base) # XXX check aq

theDOMImplementation = TransPubDOMImplementation()

#DOMIO, DOMManageable, DOMPublishable,
class TransPubNode(TransPubWrapper, DOMProxy.NodeProxy, Acquisition.Implicit):
    "The core of the TransPub DOM proxies."
    pass

class TransPubNodeList(TransPubWrapper, DOMProxy.NodeListProxy):    
    "A TransPubWrapper mixer with NodeListProxy."
    pass

class TransPubNamedNodeMap(TransPubWrapper, DOMProxy.NamedNodeMapProxy):
    "A TransPubWrapper mixer with NamedNodeMapProxy."
    pass
    
class TransPubDocumentFragment(DOMProxy.DocumentFragmentProxy, TransPubNode):
    "A TransPubWrapper mixer with DocumentFragmentProxy."
    pass
    
class TransPubElement(DOMProxy.ElementProxy, TransPubNode):
    "A TransPubWrapper mixer with ElementProxy."
    pass

class TransPubCharacterData(DOMProxy.CharacterDataProxy, TransPubNode):
    "A TransPubWrapper mixer with CharacterDataProxy."
    pass

class TransPubCDATASection(DOMProxy.CDATASectionProxy, TransPubNode):
    "A TransPubWrapper mixer with CDATASectionProxy."
    pass

class TransPubText(TextProxy, DOMProxy.TransPubCharacterData):
    "A TransPubWrapper mixer with TextProxy."
    pass

class TransPubComment(CommentProxy, DOMProxy.TransPubCharacterData):
    "A TransPubWrapper mixer with CommentProxy."
    pass

class TransPubProcessingInstruction(DOMProxy.ProcessingInstructionProxy,
                                    TransPubNode):
    "A TransPubWrapper mixer with ProcessingInstructionProxy."
    pass

class TransPubAttr(DOMProxy.AttrProxy, TransPubNode):
    "A TransPubWrapper mixer with AttrProxy."
    pass

class TransPubDocument(DOMProxy.DocumentProxy, TransPubNode):
    """
    A TransPubWrapper mixer with DocumentProxy.
    Provides and protects the implementation attribute.
    """
    
    implementation = theDOMImplementation

    #block set of implementation, since we don't proxy it the same
    def __setattr__(self, name, value):
        if name == "implementation":
            raise xml.dom.NoModificationAllowedErr()
        # wacky ExtensionClass inheritance
        TransPubDocument.inheritedAttribute('__setattr__')(self, name, value)

# DOM extended interfaces

class TransPubEntityReference(DOMProxy.EntityReferenceProxy, TransPubNode):
    "A TransPubWrapper mixer with EntityReferenceProxy."
    pass

class TransPubEntity(DOMProxy.EntityProxy, TransPubNode):
    "A TransPubWrapper mixer with EntityProxy."
    pass

class TransPubNotation(DOMProxy.NotationProxy, TransPubNode):
    "A TransPubWrapper mixer with NotationProxy."
    pass

class TransPubDocumentType(DOMProxy.DocumentTypeProxy, TransPubNode):
    "A TransPubWrapper mixer with DocumentTypeProxy."
    pass

