import re

def pathToAttribute(path):
    """
    Gets LDAP attribute name from path.
    """
    p = path.split('/')
    return p[-1]
    
def pathLastItem(path):
    s = path.split('/')
    l = len(s)
    i = 1 # forget first path element, that must be None
    while i < l:
        if s[i].endswith('\\'):
            s[i] = s[i][:-1] + '/' + s[i+1]
            del s[i+1]
            l = l - 1
        i = i + 1
    if not s[-1]:
        del s[-1] # forget last path element, that should be None
    return s[-1]

def pathToDN(path, base_dn=''):
    """
    Gets LDAP DN from path.
    """
    assert path[0] == '/', "relative path not yet supported"

    s = path.split('/')
    l = len(s)
    i = 1 # forget first path element, that must be None
    while i < l:
        if s[i].endswith('\\'):
            s[i] = s[i][:-1] + '/' + s[i+1]
            del s[i+1]
            l = l - 1
        i = i + 1
    del s[-1] # forget last path element, that should be attribute name or None
    
    s.reverse()

    dn = ''
    for p in s:
        if p:
            dn = dn + 'node=' + p + ','
    return dn + base_dn

def dnToPath(dn, base_dn):
    """
    Gets path from LDAP DN.
    """
    assert dn.endswith(base_dn)
    _dn = dn[:-len(base_dn)]
    m = re.findall(r'node=(.*?),', _dn)
    m.reverse()
    return '/' + '/'.join(m) + '/'
    

