import uuid

__author__ = 'tanshu'

from pyramid.security import Everyone
from pyramid.security import Authenticated
from pyramid.security import Allow
from .models.auth import Permission, User


class RootFactory(object):
    @property
    def __acl__(self):
        acl = [
            (Allow, Everyone, 'view'),
            (Allow, Authenticated, 'Authenticated')]
        for permission in Permission.list():
            acl.append((Allow, permission.name, permission.name))
        return acl

    def __init__(self, request):
        pass



def groupfinder(user_id, request):
    if request is not None and 'perms' in request.session:
        perms = request.session['perms']
    else:
        if type(user_id) == str:
            user_id = uuid.UUID(user_id)
        perms = []
        user = User.by_id(user_id)
        for item in user.roles:
            for perm in item.permissions:
                perms.append(perm.name)
        perms = f7(perms)
        if request is not None:
            request.session['perms'] = perms
    return perms


def f7(seq):
    seen = set()
    seen_add = seen.add
    return [x for x in seq if x not in seen and not seen_add(x)]
