import json
import logging

from urllib2 import build_opener, HTTPHandler, Request, urlopen

pocform = 'invitation'
wcs = 'http://forms-condorcet.dev.entrouvert.org/'
posturl = wcs+'/api/formdefs/'+pocform+'/submit'

INVITATION_ATTRIBUTES_MAPPING = {
    'ep_principal_name': 'hote_identite',
    'email': 'hote_courriel',
    'prenom': 'hote_prenom',
    'nom': 'hote_nom',
    's_etablissement': 'hote_etablissement',
    's_entite_affectation_principale': 'hote_unite'
}

ADDITIONAL_PREFILLED_FIELDS = ['hote_etablissement', 'hote_unite', 'hote_type']

PASSERELLE_PEOPLE_QUERY = 'http://dir-condorcet.dev.entrouvert.org/ldapquery/condorcet/run/6/'

logger = logging.getLogger('django')

def get_invitaton_attributes_mapping():
    """ Full copy of the invitation attributes mapping dictionary """
    return INVITATION_ATTRIBUTES_MAPPING.copy()

def get_additional_prefilled_fields():
    """
    Returns a full copy of the additional fields to be prefilled with the
    user's fetched attributes.
    """
    return ADDITIONAL_PREFILLED_FIELDS[:]

def do_invite(invitation):
    """
    Sends invitation data to the invitation w.c.s. form.
    Invitations will then be sent as part of the w.c.s. workflow.
    """
    opener = build_opener(HTTPHandler)
    # Generate a JSON to bind against the wcs ReST API
    form = {}
    # Forge a HTTP POST request
    form["data"] = invitation
    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 :
        ret = -1

    return ret


def get_affectations_from_eppn(eppn):
    """
    Returns a tuple (<Institution identifier>, <Researcher unit identifier>)
    for a given eduPersonPrincipalName (a.k.a. `eppn`)
    """
    if eppn:
        try:
            ldapquery = urlopen(PASSERELLE_PEOPLE_QUERY)
            jsonresult = json.loads(ldapquery.read())

            for user in jsonresult['content']:
                if user.get('attributes', {}).get('eduPersonPrincipalName') == eppn:
                    return (user['attributes'].get('supannEtablissement', [''])[0],
                            user['attributes'].get('supannEntiteAffectation', [''])[0])
            raise Exception('Invalid user')
            # fall back in except block
        except Exception, e:
            logger.error('%s' % e)
            return ('', '')
