import json
import urllib
import urllib2
import urlparse

from ldap3 import Server, Connection, ALL, SUBTREE, ALL_ATTRIBUTES

wcs_base = "http://wcs.example.com"
form_slug = "/traitement/"
base = "ou=People,dc=entrouvert,dc=lan"
scope = SUBTREE
pocform = 'traitement'


# Simple w.c.s. <-> Passerelle REST communication
def get_form_entry(wcs_entry_id):
    data_uri = "/api/forms"+form_slug+str(wcs_entry_id)
    geturl = wcs_base+data_uri

    # Simple HTTP GET request:
    req = urllib2.urlopen(geturl)
    return req.read()

# Bind to local OpenLDAP server
def ldap_init():
    # Admin DN:
    who = "cn=admin,dc=entrouvert,dc=lan"
    # Credentials: XXX
    cred = "test" #FIXME
    # The local server:
    server = Server('spare.entrouvert.lan')
    # Authenticated binding:
    conn = Connection(server, user=who, password=cred)
    res = conn.bind()
    return conn

def ldap_init3(who='', cred='', server='localhost'):
    s = Server(server)
    conn = Connection(s, user=who, password=cred)
    res = conn.bind()
    return conn

def ldap_operation(connector, data):
    handle = ldap_init3(connector.user, connector.password, connector.server) #FIXME

    # TODO
    if data['operation'] == 1:
        return 'TODO Search'
    elif data['operation'] == 2:
        return 'TODO Add'
    elif data['operation'] == 3:
        return 'TODO Modify'
    elif data['operation'] == 4:
        return 'TODO Delete'
    elif data['operation'] == 5:
        return 'TODO Generic LDIF operation'

    ldap_terminate(handle)
    return data['operation']


def ldap_terminate(conn):
    conn.unbind()
    return 0

def ldap_max_uidnumber():
    l = ldap_init()

    # We need to iterate the whole user list in
    #   the default base DN:
    l.search(search_base = base,
             search_filter = '(uid=*)',
             search_scope = scope,
             attributes = 'uidNumber')

    # What is the maximum uidNumber ?
    max_uidnumber = 0
    for entry in l.response:
        if entry['attributes']['uidNumber'] > max_uidnumber:
            max_uidnumber = entry['attributes']['uidNumber']

    ldap_terminate(l)

    return max_uidnumber

def ldap_add_entry(id):
    # Avoid any uidNumber conflict:
    uidNumber = ldap_max_uidnumber()+1

    # The newly created entry DN.
    #   (the "dn: " prefix musn't appear here):
    dn = 'uid='+id['nameid']+","+base

    objectClass = ['inetOrgPerson', 'organizationalPerson', 'person', 'posixAccount', 'top']

    # All the entry attributes can be defined in a dictionary as below:
    addmod = {}
    addmod['cn'] = id['prenom']+" "+id['nom']
    addmod['uid'] = id['nameid']
    addmod['uidNumber'] = str(uidNumber)
    addmod['gidNumber'] = '1000'
    addmod['sn'] = id['nom']
    addmod['homeDirectory'] = "/home/"+id['nameid']
    addmod['roomNumber'] = id['bureau']
    addmod['telephoneNumber'] = id['telephone']

    l = ldap_init()

    ret = l.add(dn, objectClass, addmod)

    ldap_terminate(l)

    return ret
