import urllib2

from ldap3 import Server, Connection, SUBTREE

wcs_base = "http://forms-condorcet.dev.entrouvert.org"
form_slug = "/traitement_supann/"
base = "ou=people,dc=condorcet,dc=dev,dc=entrouvert,dc=org"
pocform = 'traitement_supann'
scope = SUBTREE


# 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"
    who = "cn=admin,dc=condorcet,dc=dev,dc=entrouvert,dc=org"
    # Credentials: XXX
    cred = "test"
    # The local server:
    server = Server('condorcet.dev.entrouvert.org')
    # Authenticated binding:
    conn = Connection(server, user=who, password=cred)
    res = conn.bind()
    return conn

def ldap_init3(who='', cred='', server='condorcet.dev.entrouvert.org'):
    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_add_entry(id):
    delimiter = ','
    # The new DN
    #   (the "dn: " prefix musn't appear here):
    if 'ep_principal_name' not in id:
        return [-1, 'EPPN manquant!']

    dn = 'uid='+id.get('ep_principal_name')+","+base

    objectClass = ['inetOrgPerson', 'supannPerson', 'eduPerson']

    addmod = {}

    # All the entry attributes can be defined in a dictionary as below.
    # Only 'cn', 'uid' and 'sn' attributs are mandatory:
    addmod['cn'] = id.get('prenom')+" "+id.get('nom')
    addmod['uid'] = id.get('ep_principal_name')
    addmod['sn'] = id.get('nom')

    # eduPerson attributes:
    addmod['eduPersonPrincipalName'] = id.get('ep_principal_name')
    addmod['eduPersonPrimaryAffiliation'] = id.get('ep_primary_affiliation')

    if id.get('ep_affiliation') is not None:
        addmod['eduPersonAffiliation'] = id.get('ep_affiliation').split(delimiter)

    # supannPerson Attributes:
    addmod['supannEtablissement'] = id.get('s_etablissement')
    addmod['supannEntiteAffectationPrincipale'] = id.get('s_entite_affectation_principale')

    if id.get('supannEntiteAffectation') is not None:
        addmod['supannEntiteAffectation'] = id.get('s_entite_affectation').split(delimiter)

    addmod['supannEmpCorps'] = id.get('s_emp_corps')

    if id.get('s_liste_rouge') == True:
        addmod['supannListeRouge'] = 'TRUE'
    #elif id.get('s_liste_rouge') == False:
    else:
        addmod['supannListeRouge'] = 'FALSE'

    # Extra attributes:
    addmod['givenName'] = id.get('prenom')
    addmod['mail'] = id.get('email')

    l = ldap_init()

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

    ldap_terminate(l)

    return ret
