import tempfile, os, cStringIO, string
from Ft.Server.Server import RepositoryReader

from xml.dom import Node
from Ft.Xml.Xslt import Stylesheet

from Ft.Server.Common import ResourceTypes

import test_helper

def test_base_reader(tester):

    tester.startTest("Base Reader")
    repo = repo = test_helper.GetRepo(tester)
    reader = RepositoryReader.RepositoryReader(repo)
    res = reader.fromDb('/test/doc1')
    tester.compare(DOC1,res.getContent())
    repo.txRollback()
    tester.testDone()


def test_document_reader(tester):

    tester.startTest("Document Reader")
    repo = repo = test_helper.GetRepo(tester)
    test = repo.fetchResource("/test")
    reader = RepositoryReader.RepositoryDocumentReader(test)

    res = reader.fromUri('doc1','')
    tester.compare('docelem',res.documentElement.localName)

    res = reader.fromUri('sheet1','')
    tester.compare(Node.DOCUMENT_NODE,res.nodeType)
    tester.compare('stylesheet',res.documentElement.localName)

    repo.txRollback()
    tester.testDone()



def test_stylesheet_reader(tester):

    tester.startTest("Stylesheet Reader")
    repo = repo = test_helper.GetRepo(tester)
    test = repo.fetchResource("/test")
    reader = RepositoryReader.RepositoryStylesheetReader(test)


    res = reader.fromUri('sheet1')
    tester.compare(1,isinstance(res,Stylesheet.StylesheetElement))
    tester.compare(1,hasattr(res,'expandedName'))
    repo.txRollback()
    tester.testDone()



def init(tester):

    tester.startTest("Init")
    repo = repo = test_helper.GetRepo(tester)
    if repo.hasResource('/test'):
        t = repo.fetchResource('/test')
        t.delete()

    test = repo.createContainer("/test",1)
    test.createDocument('doc1',DOC1,forcedType=ResourceTypes.ResourceType.XML_DOCUMENT)
    repo.createDocument('/test/sheet1',SHEET1,forcedType=ResourceTypes.ResourceType.XSLT_DOCUMENT)
    repo.txCommit()
    tester.testDone()


DOC1=u"""<docelem v='foo'/>"""

SHEET1 = u"""<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
  <xsl:template match="/">
  Sheet 1
  </xsl:template>
</xsl:stylesheet>"""




def Test(tester):
    init(tester)
    test_base_reader(tester)
    test_document_reader(tester)
    test_stylesheet_reader(tester)



