#Uche Ogbuji tries a substitute reader

from Xslt import test_harness

from Ft.Lib import Uri, cDomlette
from xml.xslt.Processor import Processor

class SubstituteReader(cDomlette.RawExpatReader):
    def __init__(self):
        self._cache = {}

    def fromUri(self, uri, baseUri='', ownerDoc=None, stripElements=None):
        abs_uri = Uri.BASIC_RESOLVER.normalize(uri, base)[0]
        if self._cache.has_key(abs_uri):
            return self._cache[abs_uri]
        stream = Uri.BASIC_RESOLVER.resolve(uri, base)
        node = self.fromStream(stream, base, ownerDoc, stripElements)
        stream.close()
        return node

    def registerSubst(self, uri, node):
        self._cache[uri] = node
        return


sheet_1 = """\
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                version="1.0">

  <xsl:template match = "/">
    <xsl:value-of select='name(/*)'/>
    <xsl:text>&#10;</xsl:text>
    <xsl:value-of select='name(document("http://www.fourthought.com/4Suite/4Suite.xsa")/*)'/>
    <xsl:text>&#10;</xsl:text>
  </xsl:template>

</xsl:stylesheet>"""

source_1 = "<spam/>"

subst_1 = "<eggs/>"


expected_1 = """<?xml version='1.0' encoding='UTF-8'?>
spam
xsa
"""

#"

def Test(tester):

    tester.startGroup("Borrowed: uo_20010112")
    tester.startTest("Connect to Internet")
    import urllib
    try:
        urllib.urlopen('http://fourthought.com')
    except ImportError:
        tester.warning("Unable to connect to internet")
        tester.testDone()
        tester.groupDone()
        return
    tester.testDone()
    source = test_harness.FileInfo(string=source_1)
    sty = test_harness.FileInfo(string=sheet_1)
    xtest = test_harness.XsltTester(source,
                                    [sty],
                                    expected_1,
                                    compareFunc = cmp,
                                    )

    xtest.test(tester)
    tester.groupDone()
    return

    # FIXME - convert this to a XsltTester instance
    #Now let's substitute the 'http://www.fourthought.com/4Suite/4Suite.xsa' URI with our local string
    sreader = SubstituteReader()

    #It inherits the function of a regular cDomlette reader
    node = sreader.fromString(subst_1)
    #But now we make the switch
    sreader.registerSubst('http://www.fourthought.com/4Suite/4Suite.xsa', node)

    #So the reader we slipped in will be used throughout the processing,
    #Including by the document() function
    processor = Processor(reader=sreader)
    processor.appendStylesheetString(sheet_1)
    start = time.time()
    result = processor.runString(source_1)
    end = time.time()
    if result != expected_2:
        raise Exception('Case 2 failed.  Expected\n"""%s"""\ngot\n"""%s"""'%(repr(expected_2), repr(result)))
    print '*** Result (time: %.3f seconds) ***'%(end - start)
    print result
