"""
This module defines the interface for any DOM reader that is to
be used with XLink.  

The DOM reader must be a class that has a method Read().
The Read method uses the first argument as the source for the DOM.
It can be any value so long as the reader can turn it into a DOM
tree.  For example: a stream, string, filename or URL.

The remaining arguments are (may or may not be used as keyword arguments):
  ownerDocument - supply if the source is to be a document fragment
                  of an existing document.
  validate - use validation (boolean).
  keepAllWs - don't follow ignoreable whitespace rules (boolean)
  catName - catalog name
  stripElements - element QNames to remove whitespace from.
"""

import os, urllib
BETA = int(os.environ.get('BETA_DOMLETTE',0))
if BETA:
    try:
        from Ft.Lib import cDomlette
        Dom = cDomlette.RawExpatReader()
    except:
        BETA = 0
if not BETA:
    from Ft.Lib import pDomlette
    Dom = pDomlette.PyExpatReader()

try:
    from cStringIO import StringIO
except:
    from StringIO import StringIO

class XMLStreamReader:
    def Read(self,
             stream, ownerDoc = None):
        return Dom.fromStream(stream, doc = ownerDoc)

class StringReader(XMLStreamReader):
    def Read(self,
             source, ownerDoc = None):
        stream = StringIO(source)
        dom = XMLStreamReader.Read(self, stream,ownerDoc)
                            
        stream.close()
        return dom

class UriReader(XMLStreamReader):
    def Read(self,
             uri,ownerDoc = None):
        if os.path.exists(uri):
            stream = open(uri)
        else:
            stream = urllib.urlopen(uri)
        dom = XMLStreamReader.Read(self, stream, ownerDoc)
        stream.close()
        return dom
