
from Ft.Server.Common import CreationParams, ValidationInfo, DocumentReference, ResourceTypes

import test_helper

from Ft.Xml.Lib import TreeCompare

def test_create(tester):


    tester.startTest("Create Doc Def")

    repo = test_helper.GetRepo(tester)
    ddRoot = repo.fetchResource('/test')
    cp = CreationParams.CreationParams()
    dd = ddRoot.createXsltDocumentDefinition('def1',SRC1,cp)

    dMd = dd.getMetaDataResource().getContent()
    dContent = dd.getContent()

    cd,md = test_helper.TestMetaData(tester,
                                     dMd,
                                     dd.getPath().name,
                                     ResourceTypes.ResourceType.XSLT_DOCUMENT_DEFINITION,
                                     [],
                                     tester.test_data['userName'],
                                     'text/xml',
                                     str(len(dContent)),
                                     [],
                                     docDef = None,
                                     )

    tester.compare(DD1, dContent, func=TreeCompare.TreeCompare)

    test_helper.TestDocumentDefinitionRdf(tester,
                                          repo,
                                          dd.getAbsolutePath(),
                                          len(dContent),
                                          tester.test_data['userName'],
                                          cd,
                                          md,
                                          cp,
                                          typ=ResourceTypes.ResourceType.XSLT_DOCUMENT_DEFINITION)


    tester.compare(ResourceTypes.ResourceType.XSLT_DOCUMENT_DEFINITION,repo.hasResource('/test/def1'))
    tester.compare('/test/def1',dd.getAbsolutePath())
    test_helper.CompareCreationParams(tester,cp,dd.getCreationParams())
    repo.txCommit()


    #Make sure it persisted
    repo = test_helper.GetRepo(tester)
    dd = repo.fetchResource('/test/def1')
    tester.compare(dd,repo.fetchResource('/test').fetchResource('def1'))
    tester.compare('/test/def1',dd.getAbsolutePath())
    test_helper.CompareCreationParams(tester,cp,dd.getCreationParams())
    repo.txRollback()
    tester.testDone()


    tester.startTest("Create Derived")
    repo = test_helper.GetRepo(tester)
    ddRoot = repo.fetchResource('/test')
    cp = CreationParams.CreationParams()
    dd1 = ddRoot.fetchResource('def1')
    dd = ddRoot.createXsltDocumentDefinition('def2',SRC2,cp)
    dd.addBaseDocumentDefinition(dd1)

    dMd = dd.getMetaDataResource().getContent()
    dContent = dd.getContent()

    cd,md = test_helper.TestMetaData(tester,
                                     dMd,
                                     dd.getPath().name,
                                     ResourceTypes.ResourceType.XSLT_DOCUMENT_DEFINITION,
                                     [],
                                     tester.test_data['userName'],
                                     'text/xml',
                                     str(len(dContent)),
                                     [],
                                     docDef = None,
                                     )

    tester.compare(DD2, dContent, func=TreeCompare.TreeCompare)

    test_helper.TestDocumentDefinitionRdf(tester,
                                          repo,
                                          dd.getAbsolutePath(),
                                          len(dContent),
                                          tester.test_data['userName'],
                                          cd,
                                          md,
                                          cp,
                                          parents=[dd1.getAbsolutePath()],
                                          typ=ResourceTypes.ResourceType.XSLT_DOCUMENT_DEFINITION)

    tester.compare('/test/def2',dd.getAbsolutePath())
    test_helper.CompareCreationParams(tester,cp,dd.getCreationParams())
    tester.compare(1,len(dd.getBaseDefinitions()))
    tester.compare(dd1,dd.getBaseDefinitions()[0])
    tester.compare(1,len(dd1.getDerivedDefinitions()))
    tester.compare(dd,dd1.getDerivedDefinitions()[0])
    repo.txCommit()


    #Make sure it persisted
    repo = test_helper.GetRepo(tester)
    ddRoot = repo.fetchResource('/test')
    dd = ddRoot.fetchResource('def2')
    dd1 = ddRoot.fetchResource('def1')
    tester.compare('/test/def2',dd.getAbsolutePath())
    test_helper.CompareCreationParams(tester,cp,dd.getCreationParams())
    tester.compare(1,len(dd.getBaseDefinitions()))
    tester.compare(dd1,dd.getBaseDefinitions()[0])
    tester.compare(1,len(dd1.getDerivedDefinitions()))
    tester.compare(dd,dd1.getDerivedDefinitions()[0])
    repo.txRollback()
    tester.testDone()





    for (testName,name,cp) in [("Creation Params, Full Text Index",
                                'xml1',
                                CreationParams.CreationParams(1)),
                               ("Creation Params, w/0 Full Text Index",
                                'xml2',
                                CreationParams.CreationParams(0)),
                               ("Creation Params, Enforce Schema",
                                'xml3',
                                CreationParams.CreationParams(enforceSchema = 1)),
                               ("Creation Params, w/0 Enforce Schema",
                                'xml4',
                                CreationParams.CreationParams(enforceSchema = 0)),
                               ("Creation Params, Schematron Validation, String doc ref",
                                'xml5',
                                CreationParams.CreationParams(0,ValidationInfo.SchematronValidationInfo(DocumentReference.StringDocumentReference("A String","Base URI")))),
                               ("Creation Params, Schematron Validation, Internal doc ref",
                                'xml6',
                                CreationParams.CreationParams(0,ValidationInfo.SchematronValidationInfo(DocumentReference.InternalDocumentReference("A URI")))),
                               ("Creation Params, Schematron Validation, External doc ref",
                                'xml7',
                                CreationParams.CreationParams(0,ValidationInfo.SchematronValidationInfo(DocumentReference.ExternalDocumentReference("A URI")))),
                               ("Creation Params, DTD Validation, String doc ref",
                                'xml8',
                                CreationParams.CreationParams(1,ValidationInfo.DtdValidationInfo(DocumentReference.StringDocumentReference("A String","Base URI")))),
                               ("Creation Params, Dtd Validation, Internal doc ref",
                                'xml9',
                                CreationParams.CreationParams(0,ValidationInfo.DtdValidationInfo(DocumentReference.InternalDocumentReference("A URI")))),
                               ("Creation Params, Dtd Validation, External doc ref",
                                'xml10',
                                CreationParams.CreationParams(0,ValidationInfo.DtdValidationInfo(DocumentReference.ExternalDocumentReference("A URI")))),
                               ("Creation Params, w/0 Ext Modules",
                                'xml11',
                                CreationParams.CreationParams(extModules = ['foo'])),
                               ]:

        tester.startTest(testName)
        repo = test_helper.GetRepo(tester)
        ddRoot = repo.fetchResource('/test')
        dd = ddRoot.createXsltDocumentDefinition(name,SRC1,cp)
        dMd = dd.getMetaDataResource().getContent()
        dContent = dd.getContent()

        cd,md = test_helper.TestMetaData(tester,
                                         dMd,
                                         dd.getPath().name,
                                         ResourceTypes.ResourceType.XSLT_DOCUMENT_DEFINITION,
                                         [],
                                         tester.test_data['userName'],
                                         'text/xml',
                                         str(len(dContent)),
                                         [],
                                         docDef = None,
                                         )
        test_helper.TestDocumentDefinitionRdf(tester,
                                              repo,
                                              dd.getAbsolutePath(),
                                              len(dContent),
                                              tester.test_data['userName'],
                                              cd,
                                              md,
                                              cp,
                                              typ=ResourceTypes.ResourceType.XSLT_DOCUMENT_DEFINITION)
        test_helper.CompareCreationParams(tester,cp,dd.getCreationParams())
        repo.txCommit()

        repo = test_helper.GetRepo(tester)
        dd = repo.fetchResource('/test').fetchResource(name)
        test_helper.CompareCreationParams(tester,cp,dd.getCreationParams())
        repo.txRollback()
        tester.testDone()




def test_modify(tester):

    tester.startTest("Change Mappings")
    repo = test_helper.GetRepo(tester)
    ddRoot = repo.fetchResource('/test')
    
    dr = DocumentReference.StringDocumentReference("String", "Base")
    vi = ValidationInfo.SchematronValidationInfo(dr)
    cp = CreationParams.CreationParams(0,vi)

    dd = ddRoot.fetchResource('def2')
    dd1 = ddRoot.fetchResource('def1')
    dd.setCreationParams(cp)

    dMd = dd.getMetaDataResource().getContent()
    dContent = dd.getContent()


    cd,md = test_helper.TestMetaData(tester,
                                     dMd,
                                     dd.getPath().name,
                                     ResourceTypes.ResourceType.XSLT_DOCUMENT_DEFINITION,
                                     [],
                                     tester.test_data['userName'],
                                     'text/xml',
                                     str(len(dContent)),
                                     [],
                                     docDef = None,
                                     )


    #tester.compare(DD3,dContent,diff=1)

    test_helper.TestDocumentDefinitionRdf(tester,
                                          repo,
                                          dd.getAbsolutePath(),
                                          len(dContent),
                                          tester.test_data['userName'],
                                          cd,
                                          md,
                                          cp,
                                          parents=[dd1.getAbsolutePath()],
                                          typ=ResourceTypes.ResourceType.XSLT_DOCUMENT_DEFINITION)


    tester.compare('/test/def2',dd.getAbsolutePath())
    test_helper.CompareCreationParams(tester,cp,dd.getCreationParams())
    repo.txCommit()
    tester.testDone()

    tester.startTest("Load Changed")
    repo = test_helper.GetRepo(tester)
    ddRoot = repo.fetchResource('/test')
    dd = ddRoot.fetchResource('def2')
    tester.compare('/test/def2',dd.getAbsolutePath())
    test_helper.CompareCreationParams(tester,cp,dd.getCreationParams())
    repo.txRollback()
    tester.testDone()



def test_delete(tester):


    tester.startTest("Delete doc def")
    repo = test_helper.GetRepo(tester)
    ddRoot = repo.fetchResource('/test')

    dd = ddRoot.fetchResource('def1')
    dd.delete()
    dd2 = ddRoot.fetchResource('def2')
    tester.compare(0,len(dd2.getBaseDefinitions()))
    repo.txCommit()
    tester.testDone()

def test_xml_doc_interface(tester):

    tester.startTest("Doc Def XML document interface")

    repo = test_helper.GetRepo(tester)
    ddRoot = repo.fetchResource('/test')

    dd = ddRoot.fetchResource('def2')
    dd.getContent()
    dom = dd.asDom()
    tester.compare('stylesheet',dom.documentElement.localName)

    dom = dd.asStylesheet()
    tester.compare(1,hasattr(dom,'expandedName'))

    repo.txCommit()

    tester.testDone()


    tester.startTest("Modify Content")
    repo = test_helper.GetRepo(tester)
    ddRoot = repo.fetchResource('test')
    dd = ddRoot.fetchResource('def2')
    dd.setContent(DD4)

    tester.compare(DD4, dd.getContent(), func=TreeCompare.TreeCompare)
    cp = CreationParams.CreationParams(fullTextIndex = 1,enforceSchema = 1)
    test_helper.CompareCreationParams(tester,cp,dd.getCreationParams())
    repo.txCommit()


    repo = test_helper.GetRepo(tester)
    ddRoot = repo.fetchResource('test')
    dd = ddRoot.fetchResource('def2')

    tester.compare(DD4,dd.getContent(),func=TreeCompare.TreeCompare)
    cp = CreationParams.CreationParams(fullTextIndex = 1,enforceSchema = 1)
    test_helper.CompareCreationParams(tester,cp,dd.getCreationParams())
    repo.txRollback()

    tester.testDone()




def test_clean(tester):


    repo = test_helper.GetRepo(tester)
    tester.startTest("Remove DTD")
    if repo.hasResource('/test'):
        repo.deleteResource('/test')
    repo.createContainer("/test",1)
    repo.txCommit()
    tester.testDone()

def Test(tester):

    test_clean(tester)
    test_create(tester)
    test_modify(tester)
    test_delete(tester)
    test_xml_doc_interface(tester)
    test_clean(tester)


SRC1 = """<?xml version='1.0'?>
<xsl:stylesheet
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:ftss="http://xmlns.4suite.org/reserved"
  xmlns:rdf='http://www.w3.org/1999/02/22-rdf-syntax-ns#'
  version="1.0"
>

  <xsl:param name='ftss:path'/>

  <xsl:template match='/'>
    <rdf:RDF>
      <rdf:Description about='{$ftss:path}'>
        <Test>Test Value</Test>
      </rdf:Description>
    </rdf:RDF>
  </xsl:template>
</xsl:stylesheet>"""


SRC2 = """<?xml version='1.0'?>
<xsl:stylesheet
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:ftss="http://xmlns.4suite.org/reserved"
  xmlns:rdf='http://www.w3.org/1999/02/22-rdf-syntax-ns#'
  version="1.0"
>

  <xsl:param name='ftss:path'/>

  <xsl:template match='/'>
    <rdf:RDF>
      <rdf:Description about='{$ftss:path}'>
        <Test2>Test Value</Test2>
      </rdf:Description>
    </rdf:RDF>
  </xsl:template>
</xsl:stylesheet>"""


DD1 = """<?xml version='1.0' encoding='UTF-8'?>
<xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform' xmlns:ftss='http://xmlns.4suite.org/reserved' xmlns:rdf='http://www.w3.org/1999/02/22-rdf-syntax-ns#' version='1.0'>\n\n  <xsl:param name='ftss:path'/>\n\n  <xsl:template match='/'>\n    <rdf:RDF>\n      <rdf:Description about='{$ftss:path}'>\n        <Test>Test Value</Test>\n      </rdf:Description>\n    </rdf:RDF>\n  </xsl:template>\n<ftss:BaseNames/><ftss:CreationParams FullTextIndex='0' EnforceSchema='0'><ftss:Validator type='http://schemas.4suite.org/4ss#documentdefinition.no_validation'/></ftss:CreationParams></xsl:stylesheet>"""

DD2 = """<?xml version='1.0' encoding='UTF-8'?>
<xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform' xmlns:xlink='http://www.w3.org/1999/xlink' xmlns:ftss='http://xmlns.4suite.org/reserved' xmlns:rdf='http://www.w3.org/1999/02/22-rdf-syntax-ns#' version='1.0'>\n\n  <xsl:param name='ftss:path'/>\n\n  <xsl:template match='/'>\n    <rdf:RDF>\n      <rdf:Description about='{$ftss:path}'>\n        <Test2>Test Value</Test2>\n      </rdf:Description>\n    </rdf:RDF>\n  </xsl:template>\n<ftss:BaseNames><ftss:Base xlink:href='/test/def1' xlink:type='simple' xlink:actuate='onLoad' xlink:show='embed'/></ftss:BaseNames><ftss:CreationParams FullTextIndex='0' EnforceSchema='0'><ftss:Validator type='http://schemas.4suite.org/4ss#documentdefinition.no_validation'/></ftss:CreationParams></xsl:stylesheet>"""

DD3 = """<?xml version='1.0' encoding='UTF-8'?>
<xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform' xmlns:xlink='http://www.w3.org/1999/xlink' xmlns:ftss='http://xmlns.4suite.org/reserved' xmlns:rdf='http://www.w3.org/1999/02/22-rdf-syntax-ns#' version='1.0'>\n\n
<xsl:param name='ftss:path'/>\n\n  <xsl:template match='/'>\n    <rdf:RDF>\n      <rdf:Description about='{$ftss:path}'>\n        <Test2>Test Value</Test2>\n      </rdf:Description>\n
 </rdf:RDF>\n  </xsl:template>\n<ftss:BaseNames><ftss:Base xlink:type='simple' xlink:href='/test/def1' xlink:actuate='onLoad' xlink:show='embed'/></ftss:BaseNames><ftss:CreationParams FullTextIndex='0' EnforceSchema='0'><ftss:Validator type='http://schemas.4suite.org/4ss#documentdefinition.schematron_validation'><ftss:DocumentReference type='STRING' baseUri='Base'>String</ftss:DocumentReference></ftss:Validator></ftss:CreationParams></xsl:stylesheet>"""


DD4="""<?xml version='1.0' encoding='UTF-8'?>
<xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform' xmlns:ftss='http://xmlns.4suite.org/reserved' xmlns:rdf='http://www.w3.org/1999/02/22-rdf-syntax-ns#' version='1.0'>

  <xsl:param name='ftss:path'/>
  <xsl:template match='/'>
    <rdf:RDF>
      <rdf:Description about='{$ftss:path}'>
        <Test>Test Value</Test>
      </rdf:Description>
    </rdf:RDF>
  </xsl:template>
  <ftss:BaseNames/>
  <ftss:CreationParams EnforceSchema='1' FullTextIndex='1'>
    <ftss:Validator type='http://schemas.4suite.org/4ss#documentdefinition.no_validation'/>
  </ftss:CreationParams>
</xsl:stylesheet>"""

