import grok
from zope.component import getUtilitiesFor
from zope.interface import Interface
from zope.securitypolicy.interfaces import IRole, IPrincipalRoleMap
from waeup.sirp.interfaces import ILocalRolesAssignable

class Public(grok.Permission):
    """Everyone-can-do-this-permission.

    This permission is meant to be applied to objects/views/pages
    etc., that should be usable/readable by everyone.

    We need this to be able to tune default permissions more
    restrictive and open up some dedicated objects like the front
    page.
    """
    grok.name('waeup.Public')

class Anonymous(grok.Permission):
    """Only-anonymous-can-do-this-permission.
    """
    grok.name('waeup.Anonymous')

class ViewPermission(grok.Permission):
    grok.name('waeup.View')

class ManageUniversity(grok.Permission):
    grok.name('waeup.manageUniversity')

class ManageUsers(grok.Permission):
    grok.name('waeup.manageUsers')

class ManageDataCenter(grok.Permission):
    grok.name('waeup.manageDataCenter')

class ManagePortalConfiguration(grok.Permission):
    grok.name('waeup.managePortalConfiguration')

# Local Roles
class DepartmentOfficer(grok.Role):
    grok.name('waeup.local.DepartmentOfficer')
    grok.title(u'Department Officer')
    grok.permissions('waeup.manageUniversity','waeup.View', 'waeup.Public')

class ClearanceOfficer(grok.Role):
    grok.name('waeup.local.ClearanceOfficer')
    grok.title(u'Clearance Officer')
    # to be further defined
    grok.permissions('waeup.View', 'waeup.Public')

class CourseAdviser(grok.Role):
    grok.name('waeup.local.CourseAdviser')
    grok.title(u'Course Adviser')
    # to be further defined
    grok.permissions('waeup.View', 'waeup.Public')

# Global Roles
class PortalUser(grok.Role):
    grok.name('waeup.PortalUser')
    grok.title(u'Portal User')
    grok.permissions('waeup.View', 'waeup.Public')

class PortalManager(grok.Role):
    grok.name('waeup.PortalManager')
    grok.title(u'Portal Manager')
    grok.permissions('waeup.manageUniversity', 'waeup.manageUsers',
                     'waeup.View', 'waeup.Public','waeup.manageACBatches',
                     'waeup.manageDataCenter','waeup.managePortalSettings',
                     'waeup.managePortalConfiguration',
                     'waeup.manageApplications', 'waeup.handleApplication',
                     'waeup.viewStudent', 'waeup.manageStudents',
                     'waeup.viewHostels', 'waeup.manageHostels')

def getRoles():
    """Return a list of tuples ``<ROLE-NAME>, <ROLE>``.
    """
    return getUtilitiesFor(IRole)

def getWAeUPRoles(also_local=False):
    """Get all WAeUP roles.

    WAeUP roles are ordinary roles whose id by convention starts with
    a ``waeup.`` prefix.

    If `also_local` is ``True`` (``False`` by default), also local
    roles are returned. Local WAeUP roles are such whose id starts
    with ``waeup.local.`` prefix (this is also a convention).

    Returns a generator of the found roles.
    """
    for name, item in getRoles():
        if not name.startswith('waeup.'):
            # Ignore non-WAeUP roles...
            continue
        if not also_local and name.startswith('waeup.local.'):
            # Ignore local roles...
            continue
        yield item

def getWAeUPRoleNames():
    """Get the ids of all WAeUP roles.

    See :func:`getWAeUPRoles` for what a 'WAeUPRole' is.

    This function returns a sorted list of WAeUP role names.
    """
    return sorted([x.id for x in getWAeUPRoles()])


class LocalRolesAssignable(grok.Adapter):
    """Default implementation for `ILocalRolesAssignable`.

    This adapter returns a list for dictionaries for objects for which
    we want to know the roles assignable to them locally.

    The returned dicts contain a ``name`` and a ``title`` entry which
    give a role (``name``) and a description, for which kind of users
    the permission is meant to be used (``title``).

    Having this adapter registered we make sure, that for each normal
    object we get a valid `ILocalRolesAssignable` adapter.

    Objects that want to offer certain local roles, can do so by
    setting a (preferably class-) attribute to a list of role ids.

    You can also define different adapters for different contexts to
    have different role lookup mechanisms become available. But in
    normal cases it should be sufficient to use this basic adapter.
    """
    grok.context(Interface)
    grok.provides(ILocalRolesAssignable)

    _roles = []

    def __init__(self, context):
        self.context = context
        role_ids = getattr(context, 'local_roles', self._roles)
        self._roles = [(name, role) for name, role in getRoles()
                       if name in role_ids]
        return

    def __call__(self):
        """Get a list of dictionaries containing ``names`` (the roles to
        assign) and ``titles`` (some description of the type of user
        to assign each role to).
        """
        return [
            dict(
                name=name,
                title=role.title,
                description=role.description)
            for name, role in self._roles]

def get_users_with_local_roles(context):
    """Get a list of dicts representing the local roles set for `context`.

    Each dict returns `user_name`, `user_title`, `local_role`,
    `local_role_title`, and `setting` for each entry in the local
    roles map of the `context` object.
    """
    try:
        role_map = IPrincipalRoleMap(context)
    except TypeError:
        # no map no roles.
        raise StopIteration
    for local_role, user_name, setting in role_map.getPrincipalsAndRoles():
        user = grok.getSite()['users'].get(user_name,None)
        user_title = getattr(user, 'description', user_name)
        local_role_title = dict(getRoles())[local_role].title
        yield dict(user_name = user_name,
                   user_title = user_title,
                   local_role = local_role,
                   local_role_title = local_role_title,
                   setting = setting)
