import functools

import flask

from webapp import config

def validate(predicate, arg, error='Error!', redirect='/'):
    def decorator(f):
        @functools.wraps(f)
        def func(**kw):
            v = kw.get(arg)
            if predicate(v):
                return f(**kw)
            else:
                flask.flash(error, category='error')
                return flask.redirect(redirect)
        return func
    return decorator

def sanitize_perms():
    config.can = { k: set(map(sanitize_ldap, v)) for k,v in config.can.items() }

def sanitize_readable():
    config.readable_names = { sanitize_ldap(k): v for k, v in config.readable_names.items() }

def sanitize_ldap(k):
    k = k.lower()
    return (k in config.full_name and config.full_name[k]) or k

