import random
import string
import hashlib

import flask
import ldap

from webapp import app, config, validation

class Attr(object):
    def __init__(self, name, value):
        name = validation.sanitize_ldap(name)
        self.name = name
        self.readable_name = config.readable_names.get(name, name)
        self.value = value
        self.uid = hashlib.sha1(name.encode('utf-8') + value).hexdigest()
    def __str__(self):
        return self.value.decode('utf-8')

def get_dn():
    return flask.session.get('dn')

def get_connection(dn = None):
    dn = dn or get_dn()
    return app.connections[dn]

def get_admin_connection():
    conn = app.connections[config.admin_dn]
    if not conn:
        conn = app.connections.bind(config.admin_dn, config.admin_pw)
    return conn

def get_profile():
    return app.profiles[get_dn()]

def refresh_profile(dn=None):
    dn = dn or get_dn()
    conn = get_connection(dn)
    if not conn:
        return # no session, nothing to refresh i guess
    res = conn.search_s(dn, ldap.SCOPE_SUBTREE)
    assert(len(res) == 1)
    profile = {}
    for attr, vs in res[0][1].items():
        for v in vs:
            a = Attr(attr, v)
            profile[a.uid] = a
    app.profiles[dn] = profile
    return profile

def generate_token():
    dn = get_dn()
    token = ''.join(random.choice(string.letters) for i in xrange(config.TOKEN_LENGTH))
    app.tokens.insert(dn, token)

def get_token():
    dn = get_dn()
    return app.tokens[dn]


