import time

import test_helper

from Ft.Server.Common import Schema

def _init(tester):
    tester.startTest("Clean and Init")
    repo = test_helper.GetRepo(tester)
    if repo.hasResource('/test'):
        repo.deleteResource('/test')

    test = repo.createContainer('/test',1)

    test.createDocument('doc1',DOC1)
    test.createDocument('doc2',DOC2)

    repo.txCommit()
    tester.testDone()


def test_temp_files(tester):
    tester.startTest("Create a temp file (should take ~20 secs)")
    repo = test_helper.GetRepo(tester)

    repo.setPathTemporary('/test/doc1',10)
    doc2 = repo.fetchResource('/test/doc2')
    doc2.markTemporary(20)

    m = repo.getModel()
    tester.compare(1,len(m.complete('/test/doc1',Schema.TIME_TO_LIVE,None)))
    tester.compare(1,len(m.complete('/test/doc2',Schema.TIME_TO_LIVE,None)))
    repo.txCommit()


    time.sleep(10)
    #Test as anon to make sure we can do what we need to unprivileged
    repo = test_helper.GetAnonRepo(tester)
    repo.purgeTemporaryResources()

    tester.compare(0,repo.hasResource('/test/doc1'))
    doc2 = repo.fetchResource('/test/doc2')
    m = repo.getModel()
    tester.compare(0,len(m.complete('/test/doc1',Schema.TIME_TO_LIVE,None)))
    tester.compare(1,len(m.complete('/test/doc2',Schema.TIME_TO_LIVE,None)))
    repo.txCommit()

    time.sleep(10)
    repo = test_helper.GetRepo(tester)
    repo.purgeTemporaryResources()

    tester.compare(0,repo.hasResource('/test/doc2'))
    m = repo.getModel()
    tester.compare(0,len(m.complete('/test/doc2',Schema.TIME_TO_LIVE,None)))
    repo.txCommit()

    tester.testDone()


    pass



DOC1="""<docelem v='foo'/>"""
DOC2="""<docelem w='foo'/>"""


def Test(tester):
    tester.startGroup("Temporary Files")
    _init(tester)
    test_temp_files(tester)
    tester.groupDone()

