########################################################################
# $Header: /var/local/cvsroot/4Suite/Ft/Server/Server/SCore/__init__.py,v 1.14 2004/02/01 03:10:50 jkloth Exp $
"""
Core repository access functions

Copyright 2003 Fourthought, Inc. (USA).
Detailed license and copyright information: http://4suite.org/COPYRIGHT
Project home, documentation, distributions: http://4suite.org/
"""

import os

from Ft.Server.Server import FtServerServerException, Error
from Ft.Server.Server.Lib import LogUtil


def GetRepository(userName, passwd, logger, properties, verify=0):
    from Ft.Server.Server import Drivers
    driver = Drivers.Begin(logger, properties)
    driver.login(userName, passwd, verify)
    return _GetRepository('/', driver, logger, None)


def RetrieveSession(sessionId, key, logger, properties):
    from Ft.Server.Server import Drivers
    driver = Drivers.Begin(logger, properties)
    driver.retrieveSession(sessionId, key)
    return _GetRepository('/', driver, logger, sessionId)


def _GetRepository(documentRoot, driver, logger, sessionId):
    # A repository is any container in the system that is
    # acting like the doc root. (it may in fact be /).
    from Ft.Server.Server.Drivers import PathImp
    from Ft.Server.Common import ResourceTypes

    # Normalize the path in case someone gets fancy
    documentRoot = PathImp.CreateInitialPath(documentRoot, driver)

    if not driver.hasResource(documentRoot):
        logger.warning("Attempted to access unknown document root: %s" % documentRoot.absolutePath)
        raise FtServerServerException(Error.UNKNOWN_PATH,
                                      path=documentRoot.absolutePath)
    if driver.getType(documentRoot) != ResourceTypes.ResourceType.CONTAINER:
        logger.warning("Attempted to access invalid document root: %s" % documentRoot.absolutePath)
        raise FtServerServerException(Error.INVALID_PATH,
                                      path=documentRoot.absolutePath,
                                      type='Container')

    # Create the repository
    import RepositoryImp
    repo = RepositoryImp.RepositoryImp(documentRoot, driver, sessionId)
    return repo
