# -*- coding: UTF-8 -*-


# Expression
# By: Frederic Peters <fpeters@entrouvert.com>
#     Emmanuel Raviart <eraviart@entrouvert.com>
#
# Copyright (C) 2004 Entr'ouvert, Frederic Peters & Emmanuel Raviart
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.


"""XPath Module"""


import libxml2

import environs
import locations
import logs
import namespaces


def _getActionUrl(ctx, action):
    try:
        dataHolder = environs.getVar("currentStation").getDataHolder()
        return dataHolder.getActionUri(action)
    except:
        logs.exception(
            """An exception occured in XPath function "getActionUrl":""")
        raise


def _if(ctx, condition, trueValue, falseValue):
    try:
        if condition:
            return trueValue
        else:
            return falseValue
    except:
        logs.exception("""An exception occured in XPath function "if":""")
        raise


def evaluateXpath(xpath, contextNode):
    if contextNode is None:
        return []
    if not xpath:
        return [contextNode]
    if isinstance(contextNode, libxml2.xmlDoc):
        doc = contextNode
        contextNode = doc.getRootElement()
    else:
        doc = contextNode.doc
    if doc is None:
        return []
    xpathContext = environs.getVar("application").xpathContext
    if xpathContext.contextDoc() != doc:
        xpathContext.setContextDoc(doc)
    # LibXML2 Python binding bug: contextNode() fails when the context node
    # is None. 
    # if xpathContext.contextNode() != contextNode:
    #     xpathContext.setContextNode(contextNode)
    xpathContext.setContextNode(contextNode)
    try:
        return xpathContext.xpathEval(xpath)
    except libxml2.xpathError:
        raise libxml2.xpathError("xmlXPathEval(%s) failed" % xpath)


def registerFunctions(xpathContext):
    # We don't use None as namespace URI, because it seems the XForms "if"
    # function only accepts strings for trueValue and falseValue.
    xpathContext.registerXPathFunction(
        "getActionUrl", namespaces.yep.uri, _getActionUrl)
    xpathContext.registerXPathFunction("if", namespaces.yep.uri, _if)


def unregisterFunctions(xpathContext):
    # It seems there is no way to unregister only one XPath function.
    pass
