import ldap
import json
import logging

from urllib2 import build_opener, HTTPHandler, Request, HTTPError
from random import randint
from django.utils.translation import ugettext as _

rootdn = 'dc=condorcet,dc=dev,dc=entrouvert,dc=org'
people_base = 'ou=people,'+rootdn
structures_base = 'ou=structures,'+rootdn
groups_base = 'ou=Groups,'+rootdn

scope = ldap.SCOPE_SUBTREE
pocform = 'traitement_supann'
wcs = 'http://forms-condorcet.dev.entrouvert.org/'
posturl = wcs+'/api/formdefs/'+pocform+'/submit'

logger = logging.getLogger('django')

sso_attributes = ['prenom',
                  'nom',
                  'email',
                  'ep_principal_name',
                  'ep_primary_affiliation',
                  'ep_affiliation',
                  's_etablissement',
                  's_entite_affectation_principale',
                  's_entite_affectation',
                  's_emp_corps',
                  's_liste_rouge']


def generate_eppn(lastname):
    return "%s-%06d@campus-condorcet.fr"%(lastname, randint(0,pow(10,6)))

def craft_user_nickname(mellon_dict):
    prenom = mellon_dict.get('prenom')[0]
    nom = mellon_dict.get('nom')[0]
    return " "+prenom+" "+nom

def ldap_init():
    # The server's hostname:
    server = "condorcet.dev.entrouvert.org"
    # Admin DN:
    who = "cn=admin,dc=condorcet,dc=dev,dc=entrouvert,dc=org"
    # Credentials: XXX
    cred = "test"

    try:
        l = ldap.open(server)
        l.simple_bind(who, cred)
    except ldap.LDAPError:
        logger.error('Error while binding to the OpenLDAP server.')
        l = None
    return l
# Used to fill the choices in hote_etablissemnt form ChoiceField:
def ldap_get_etablissements():
    l_handle = ldap_init()
    res = l_handle.search(structures_base, scope, '(objectClass=supannOrg)')
    rtype, rdata = l_handle.result(res, 1)
    ldap_terminate(l_handle)

    choices = []

    for etablissement in rdata:
        etablissement_data = etablissement[1]
        ou = etablissement_data['ou'][0]
        description = etablissement_data.get('description', [_('No description')])[0]
        choices.append((ou, ou+" - "+description))

    return choices

# Used to fill the choices in hote_unite form ChoiceField:
def ldap_get_unites():
    l_handle = ldap_init()
    res = l_handle.search(structures_base, scope, '(supannTypeEntite=*)')
    rtype, rdata = l_handle.result(res, 1)
    ldap_terminate(l_handle)

    choices = []

    for unite in rdata:
        unite_data = unite[1]
        ou = unite_data['ou'][0]
        description = unite_data.get('description', [_('No description')])[0]
        choices.append((ou, ou+" - "+description))

    return choices


def ldap_terminate(l):
    l.unbind()

def ldap_contains_user(id):
    # The way we derive UIDs from the id dict
    #   is defined in ldap_craft_uid:
    filter = "uid="+ldap_craft_uid(id)

    l = ldap_init()

    # Look for a user possessing the same uid:
    res = l.search(people_base, scope, filter, None)
    rtype, rdata = l.result(res, 0)

    ldap_terminate(l)

    # Does this user already is in the LDAP directory ?
    return 1 if rdata else 0

def ldap_craft_uid(id):
    return id['ep_principal_name']

def saml_collect_data(request):
    form = {}

    # Build the SSO operation summary:
    if 'mellon_session' in request.session: 
        for attribute in sso_attributes:
            attribute_element = request.session['mellon_session'][attribute][0]
            form[attribute] = str(attribute_element)

    return form

def wcs_submit(id):
    opener = build_opener(HTTPHandler)
    # Generate a JSON to bind against the wcs ReST API
    form = {}
    form["data"] = id # see wcs documentation
    data = json.dumps(form)

    req = Request(posturl, data)
    req.add_header("Content-Type", "application/json")
    req.add_header("Accept", "application/json")

    ret = 0
    try:
        opener.open(req)
    except HTTPError, e:
        logger.error('HTTP error '+ str(e.code) +'during WCS form submission')
        ret = -1

    return ret
