import random

import cmislib
import pytest


def pytest_addoption(parser):
    parser.addoption("--cmis-connector-url", help="Url of a passerelle CMIS connector instance")
    parser.addoption("--cmis-endpoint", help="Url of a passerelle CMIS endpoint")
    parser.addoption("--cmis-username", help="Username for the CMIS endpoint")
    parser.addoption("--cmis-password", help="Password for the CMIS endpoint")
    parser.addoption("--preserve-tree", action="store_true", default=False, help="Preserve test directory")


@pytest.fixture(scope='session')
def cmisclient(request):
    return cmislib.CmisClient(
        request.config.getoption("--cmis-endpoint"),
        request.config.getoption("--cmis-username"),
        request.config.getoption("--cmis-password"),
    )


@pytest.fixture(scope='session')
def cmis_connector(request):
    return request.config.getoption("--cmis-connector-url")


@pytest.fixture(scope='session')
def cmis_tmpdir(cmisclient, request):
    path = 'test-%s' % random.randint(0, 10000)
    folder = cmisclient.defaultRepository.rootFolder.createFolder(path)
    yield folder.properties['cmis:path']
    preserve_tree = request.config.getoption("--preserve-tree")
    if not preserve_tree:
        folder.deleteTree()
