from XPtrException import XPtrException
from Ft.Lib import Uri
import Ft.Lib
import os
from xml.FtCore import FtException

BETA_DOMLETTE = os.environ.get("BETA_DOMLETTE")
if BETA_DOMLETTE:
    from Ft.Lib import cDomlette
    g_domModule = cDomlette
    g_readerClass = cDomlette.RawExpatReader
else:
    from Ft.Lib import pDomlette
    g_domModule = pDomlette
    g_readerClass = pDomlette.PyExpatReader


from xml.sax.saxlib import SAXException, SAXParseException
import urllib

def SelectUri(uri, contextNode=None, nss=None, reader=g_readerClass(),
              baseUri=''):
    """
    Takes a URI and splits it into an url and fragment that can be
    consumed by SelectNode.
    """
    import urllib
    base, fragment = urllib.splittag(uri)
    if fragment is None:
        return reader.fromUri(uri, baseUri=baseUri)
    fragment = urllib.unquote(fragment)
    try:
        doc = reader.fromUri(base, baseUri=baseUri)
    except SAXException, e:
        raise XPtrException(XPtrException.RESOURCE_ERROR, e)
    except FtException, e:
        raise e
    except:
        import traceback
        traceback.print_exc()
        raise XPtrException(XPtrException.RESOURCE_ERROR)
    return SelectNode(doc, fragment, nss, contextNode)

from XPointerParserBase import SyntaxException, InternalException


def SelectNode(doc, fragment, nss=None, contextNode=None):
    """
    Accepts a valid DOM node and a unescaped fragment.
    """
    try:
        import XPointerParserc
        parser = XPointerParserc.new()
    except:
        import XPointerParser
        parser = XPointerParser.new()
    try:
        xptr = parser.parse(fragment)
    except SyntaxException, e:
        raise XPtrException(XPtrException.SYNTAX_ERROR, e)
    except InternalException, e:
        raise XPtrException(XPtrException.SYNTAX_ERROR, e)
    except:
        raise XPtrException(XPtrException.SYNTAX_ERROR)
    context = XPtrContext.XPtrContext(doc, 1, 1, contextNode or doc, nss or {})
    return xptr.select(context)


def Init():
    import xml.xpath
    xml.xpath.RegisterExtensionModules(['Ft.XPointer.XPtrFunctions'])

Init()
    
