"""$URL: svn://svn/repos/trunk/dulcinea/lib/user_database.py $
$Id: user_database.py 21272 2003-04-02 20:30:21Z dbinger $

Provides the UserDatabase class.
"""

from dulcinea.base import DulcineaPersistent, new_persistent_map
from dulcinea.sort import lexical_sort
from dulcinea.errors import ConflictError

class DulcineaUserDatabase(DulcineaPersistent):
    """
    Class to hold all users in the system.  User IDs are always looked
    up in the user database, so you will generally not be able to use
    a user until it has been added to the user database.

    Instance attributes:
      users : PersistentMapping { user_id:string : user:User }
        all known users
    """

    def __init__ (self):
        self.users =  new_persistent_map()

    def get_user_ids (self):
        return self.users.keys()

    def get_users (self, sort=0):
        users = self.users.values()
        if sort:
            users = lexical_sort(users)
        return users

    def get_user (self, user_id):
        """Return the User object with id 'user_id', or None if no such
        user."""
        return self.users.get(user_id)

    def __getitem__ (self, user_id):
        return self.users[user_id]

    def add_user (self, user):
        """Add User object 'user' to the user database.  Raises
        ConflictError if there is already a user with the same user
        ID.
        """
        if self.users.has_key(user.id):
            raise ConflictError, \
                  "user '%s' already exists in the user database" % \
                  user.id
        self.users[user.id] = user


