"""
Watchers that apply modifications to lechat LDAP tree.
"""
import ldap, base64
from lechat.Utils import *

try:
    from hashlib import md5
except ImportError:
    from md5 import new as md5

def onModify(db, cred, changes):
    dn = pathToDN(changes.path, db.base_dn)
    # print 'modify LDAP entry "%s" (%s) to %s' % (dn,changes.path,changes.new)
    modlist = []
    for k, v in changes.new.items():
        if v == [ True ]:
            v = 'TRUE'
        elif v == [ False ]:
            v = 'FALSE'
        if v != []:
            if k == 'node':
                continue
            elif k == 'userPassword':
                v = [ '{MD5}' + base64.b64encode( md5(v[0]).digest() ) ]
            modlist.append( (ldap.MOD_REPLACE, k, v) )
            
    l = db._connect(cred)

    if modlist:
        l.modify_s(dn, modlist)
    
def onRename(db, cred, changes):
    dn = pathToDN(changes.path, db.base_dn)
    # print 'renaming %s to %s' %(dn, changes.new)
    l = db._connect(cred)
    try:
        l.modrdn_s(dn, 'node=%s' % changes.new)
    except:
        pass

def onCreate(db, cred, changes):
    dn = pathToDN(changes.path, db.base_dn)
    # print 'create new LDAP entry \n\tdn=%s (was %s),\n\tchanges=%s' % (dn, changes.path, changes)
    node = pathLastItem(changes.path)
    l = db._connect(cred)
    try:
        l.add_s(dn, [ ('objectClass', ['lechatNode', 'lechatMailAccount']), ('node', node) ]  )
    except ldap.ALREADY_EXISTS:
        pass

def onDelete(db, cred, changes):
    # print 'delete LDAP entry %s' % changes
    dn = pathToDN(changes.path, db.base_dn)
    l = db._connect(cred)
    l.delete_s(dn)


