import os, sha
from Ft import GetConfigVar
from Ft.Server import FTSERVER_NAMESPACE
from Ft.Server.Common import AclConstants
from Ft.Server.Common.ResourceTypes import ResourceType

from Server.Client.Core import test_helper

BASE_CONTAINER = 'cltest'

COMMAND_STUB = """<?xml version="1.0" encoding="UTF-8"?>
<ftss:Command xmlns:ftss="%s" full-name="%%s"/>
""" % FTSERVER_NAMESPACE

def InitRepo(tester,custom,command):

    tester.startGroup("Init the repo for command line tests")

    tester.startTest("Init %s" % BASE_CONTAINER)

    repo = test_helper.GetRepo(tester)
    if repo.hasResource(BASE_CONTAINER):
        repo.deleteResource(BASE_CONTAINER)
    repo.createContainer(BASE_CONTAINER)

    ddRoot = repo.fetchResource('/ftss/docdefs')
    if ddRoot.hasResource('def1'):
        ddRoot.deleteResource('def1')
    if ddRoot.hasResource('def2'):
        ddRoot.deleteResource('def2')

    if repo.hasResource('/ftss/data'):
        repo.deleteResource('/ftss/data')
    data = repo.createContainer('/ftss/data')
    path = os.path.join(GetConfigVar('DATADIR'), 'Data', 'Stylesheets',
                        'cl-container.xslt')
    data.createDocument('cl-container.xslt', open(path).read())

    uuRoot = repo.fetchResource('/ftss/users')
    if uuRoot.hasResource('test1'):
        uuRoot.deleteResource('test1')
    if uuRoot.hasResource('test2'):
        uuRoot.deleteResource('test2')

    if uuRoot.hasResource('testUser'):
        uuRoot.deleteResource('testUser')
    uuRoot.createUser('testUser',sha.new('testUser').hexdigest())

    #Add the command to be tested, just stuff some crap in for now
    CreateCommand(repo,command)

    custom(repo)
    repo.txCommit()

    tester.testDone()
    tester.groupDone()


def CreateCommand(repo, command):
    name = '.'.join(command)
    repoFile = '/ftss/commands/' + name
    if repo.hasResource(repoFile):
        repo.deleteResource(repoFile)

    doc = repo.createDocument(repoFile, COMMAND_STUB % name)
    doc.setAcl(AclConstants.EXECUTE_ACCESS,AclConstants.USERS_GROUP_NAME,1)

