"""$URL: svn+ssh://svn.mems-exchange.org/repos/trunk/dulcinea/lib/user_database.py $
$Id: user_database.py 23268 2003-12-04 12:26:43Z dbinger $

Provides the UserDatabase class.
"""

from dulcinea.base import DulcineaPersistent, PersistentMapping
from dulcinea.sort import lexical_sort
from dulcinea.errors import ConflictError
from dulcinea.permission import PermissionManager
from dulcinea.user import Contact

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:DulcineaUser }
        all known users
    """

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

    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

    def get_admin(self):
        """Subclasses should override to return a PermissionManager
        """
        return None


class ContactDatabase(DulcineaUserDatabase):
    """
    Instance attributes:
      admin: PermissionManager
    """
    def __init__(self):
        DulcineaUserDatabase.__init__(self)
        system_user = Contact("SYSTEM")
        self.add_user(system_user)
        self.admin = ContactAdmin()
        self.admin.set_permission('system', system_user)

    def get_admin(self):
        return self.admin

class ContactAdmin(DulcineaPersistent, PermissionManager):
    """
    Instance attributes: none
    """
    valid_permissions = {
        "manage-permissions":
            "Allow changing of permissions.",
        "staff":
            ("Is a member of the staff, with all of the privileges and "
             "responsibilities thereunto appertaining."),
        "act-as":
            "Allow to act as another user.",
        "system":
            "Allow to do things normally done by the software system."
        }

    def __init__(self):
        PermissionManager.__init__(self)

    def __str__(self):
        return 'admin'


