import time

from Ft.Server.Server import FtServerServerException, Error
from Ft.Server.Common import AclConstants,ResourceTypes, Schema


import test_helper

def test_create(tester):


    tester.startTest("Create Raw File")
    repo = test_helper.GetRepo(tester)


    test = repo.fetchResource("/test")
    rf = test.createRawFile('rf1','text/plain',RAW1)

    rfMd = rf.getMetaDataResource().getContent()
    rfContent = rf.getContent()

    cd,md = test_helper.TestMetaData(tester,
                                     rfMd,
                                     'rf1',
                                     ResourceTypes.ResourceType.RAW_FILE,
                                     [],
                                     tester.test_data['userName'],
                                     'text/plain',
                                     str(len(rfContent)),
                                     []
                                     )

    test_helper.TestRawFileRdf(tester,
                               repo,
                               rf.getPath().absolutePath,
                               len(rfContent),
                               tester.test_data['userName'],
                               cd,
                               md,
                               'text/plain')

    tester.compare(ResourceTypes.ResourceType.RAW_FILE,test.hasResource('rf1'))
    tester.compare(rf,test.fetchResource('rf1'))
    tester.compare(ResourceTypes.ResourceType.RAW_FILE,rf.getResourceType())
    tester.compare(1,rf.isResourceType(ResourceTypes.ResourceType.RAW_FILE))
    tester.compare(0,rf.isResourceType(ResourceTypes.ResourceType.XML_DOCUMENT))
    repo.txCommit()

    repo = test_helper.GetRepo(tester)
    test = repo.fetchResource("/test")
    tester.compare(ResourceTypes.ResourceType.RAW_FILE,test.hasResource('rf1'))
    repo.txRollback()

    repo = test_helper.GetRepo(tester)
    rf = repo.fetchResource("/test/rf1")
    test = repo.fetchResource('/test')
    tester.compare(test,rf.getParent())
    repo.txRollback()

    tester.testDone()
    return



def test_access(tester):


    tester.startTest("Raw File Access")

    repo = test_helper.GetRepo(tester)

    rf = repo.fetchResource('/test/rf1')

    rfContent = rf.getContent()
    rfMd = rf.getMetaDataResource().getContent()

    cd,md = test_helper.TestMetaData(tester,
                                     rfMd,
                                     'rf1',
                                     ResourceTypes.ResourceType.RAW_FILE,
                                     [],
                                     tester.test_data['userName'],
                                     'text/plain',
                                     str(len(rfContent)),
                                     []
                                     )

    tester.compare(RAW1,rfContent)
    test_helper.TestRawFileRdf(tester,
                               repo,
                               rf.getPath().absolutePath,
                               len(rfContent),
                               tester.test_data['userName'],
                               cd,
                               md,
                               'text/plain')


    repo.txRollback()
    tester.testDone()


    tester.startTest("Raw File Access")

    repo = test_helper.GetRepo(tester)
    rf = repo.fetchResource("/test/rf1")
    tester.compare('text/plain',rf.getImt())
    tester.compare(RAW1,rf.getContent())
    tester.compare(len(RAW1),rf.getSize())
    tester.compare(None,rf.getValidationInfo())
    #Just call, don't test
    rf.getCreationDate()
    rf.getLastModifiedDate()
    repo.txRollback()

    tester.testDone()


def test_modify(tester):


    tester.startTest("Raw File Modification")

    repo = test_helper.GetRepo(tester)
    rf = repo.fetchResource("/test/rf1")
    lmd = rf.getLastModifiedDate()
    time.sleep(1)
    rf.setImt('image/jpg')
    rf.setContent(RAW2)
    tester.compare('image/jpg',rf.getImt())
    tester.compare(RAW2,rf.getContent())
    tester.compare(len(RAW2),rf.getSize())

    rfMd = rf.getMetaDataResource().getContent()
    rfContent = rf.getContent()

    cd,md = test_helper.TestMetaData(tester,
                                     rfMd,
                                     'rf1',
                                     ResourceTypes.ResourceType.RAW_FILE,
                                     [],
                                     tester.test_data['userName'],
                                     'image/jpg',
                                     str(len(rfContent)),
                                     []
                                     )

    test_helper.TestRawFileRdf(tester,
                               repo,
                               rf.getPath().absolutePath,
                               len(rfContent),
                               tester.test_data['userName'],
                               cd,
                               md,
                               'image/jpg')
    repo.txCommit()

    repo = test_helper.GetRepo(tester)
    rf = repo.fetchResource("/test/rf1")
    tester.compare('image/jpg',rf.getImt())
    tester.compare(RAW2,rf.getContent())
    tester.compare(len(RAW2),rf.getSize())
    tester.compare(1,rf.getLastModifiedDate() > lmd)
    repo.txRollback()

    tester.testDone()


def test_delete(tester):

    tester.startTest("Delete Raw File")
    repo = test_helper.GetRepo(tester)

    rf = repo.fetchResource("/test/rf1")
    fp = rf.getPath().absolutePath
    test = rf.getParent()
    rf.delete()
    tester.compare(0,test.hasResource('rf1'))
    tester.compare(0,len(repo.getModel().complete(fp,None,None)))
    tester.compare(0,len(repo.getModel().complete(test.getPath().absolutePath,Schema.CONTAINER_CHILD,None)))
    tester.testException(rf.getContent,(),FtServerServerException,{'code':Error.OBJECT_DELETED})
    repo.txCommit()
    tester.testDone()




def test_xml_interfaces(tester):

    tester.startTest("Raw File to DOM")
    repo = test_helper.GetRepo(tester)
    test = repo.fetchResource("/test")
    doc1 = test.createRawFile('doc1','text/xml',DOC1)

    dom = doc1.asDom()
    tester.compare('docelem',dom.documentElement.nodeName)
    repo.txCommit()
    tester.testDone()

    tester.startTest("Raw File to Stylesheet")
    repo = test_helper.GetRepo(tester)
    test = repo.fetchResource("/test")
    sheet1 = test.createRawFile('sheet1','text/xml',SHEET1)

    dom = sheet1.asDom()
    tester.compare('stylesheet',dom.documentElement.localName)

    dom = sheet1.asStylesheet()
    tester.compare(1,hasattr(dom,'expandedName'))
    repo.txCommit()
    tester.testDone()

    tester.startTest("Raw File to Schematron")
    repo = test_helper.GetRepo(tester)
    test = repo.fetchResource("/test")
    schema1 = test.createRawFile('schema1','text/xml',SCHEMA1)

    dom = schema1.asDom()
    tester.compare('schema',dom.documentElement.localName)

    dom = schema1.asSchematron()
    tester.compare(1,hasattr(dom,'expandedName'))
    repo.txCommit()
    tester.testDone()

    tester.startTest("Apply Xslt")
    repo = test_helper.GetRepo(tester)
    test = repo.fetchResource("/test")
    doc1 = test.fetchResource('doc1')
    sheet1 = test.fetchResource('sheet1')

    res,imt =  doc1.applyXslt([sheet1])
    tester.compare('text/plain', imt)
    tester.compare("\n  Sheet 1\n  ", res)

    repo.txRollback()
    tester.testDone()



def cleanup(tester):

    tester.startTest("Clean Up")
    repo = test_helper.GetRepo(tester)
    if repo.hasResource('/test'):
        t = repo.fetchResource('/test')
        t.delete()
    repo.createContainer("/test",1)
    repo.txCommit()
    tester.testDone()


RAW1 = "This is a text file"
RAW2 = "This is a different text file"
DOC1 = "<docelem v='foo'/>"
SHEET1 = """<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
  <xsl:output method="text"/>
  <xsl:template match="/">
  Sheet 1
  </xsl:template>
</xsl:stylesheet>"""

SCHEMA1="""<schema xmlns='http://www.ascc.net/xml/schematron'>

  <pattern name='Root'>
    <rule context="/docelem">
      <assert test='@v'>
        VALIDATION ERROR: The root element must have a v attribute
      </assert>
    </rule>
  </pattern>

</schema>"""

PARENT_CONTAINER_CONTENT="""<?xml version='1.0' encoding='UTF-8'?><ftss:Container xmlns:ftss='http://xmlns.4suite.org/reserved'>\n  <ftss:Children>\n    <ftss:Child path='/test/rf1'>\n    </ftss:Child>\n  </ftss:Children>\n</ftss:Container>"""



def Test(tester):

    cleanup(tester)
    test_create(tester)
    test_access(tester)
    test_modify(tester)
    test_delete(tester)
    test_xml_interfaces(tester)


