import logging
from django.shortcuts import redirect
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext_lazy as _

from .utils import ldap_contains_user, saml_collect_data, \
        ldap_get_affectations, render_message, ldap_get_code_etablissements

from .views import MSG_USERNONE

logger = logging.getLogger('django')

MSG_USER_REGISTERED = _("Your account is already registered to the Campus.")

MSG_STRUCT_NOT_IN_CAMPUS = _("You are not allowed to register to the Campus.")

MSG_USER_NOT_REGISTERED = _("Please register to the campus before sending "
                            "invites.")

def user_not_in_ldap(function):
    """
    Restricts access to users whose eduPersonPrincipalName attribute value
    doesn't appear in a ou=people sub-entry in the Campus LDAP.
    """
    def wrapped(request, *args, **kwargs):
        if 'type' in kwargs and kwargs['type'] == 'mellon':
            user_data = saml_collect_data(request)
            if ldap_contains_user(user_data):
                logger.info(u'usernone error for request %s' % request)
                return render_message(request, MSG_USERNONE)
        return function(request, *args, **kwargs)
    return wrapped

def user_in_ldap(function):
    """
    Restricts access to users whose eduPersonPrincipalName attribute value
    appear in a `ou=people...` sub-entry in the Campus LDAP.
    """
    def wrapped(request, *args, **kwargs):
        if 'host_type' not in request.session:
            if request.GET.get('host_type') == 'member':
                request.session['host_type'] = 'member'
            else:
                request.session['host_type'] = 'affiliate'
        if not 'mellon_session' in request.session:
            return redirect(reverse('auth_login') + "?next="+request.path)
        user_data = saml_collect_data(request)
        if not ldap_contains_user(user_data):
            logger.info(u'user not registered error for request %s' % request)
            return render_message(request, MSG_USER_NOT_REGISTERED)
        return function(request, *args, **kwargs)
    return wrapped

def user_can_declare(function):
    """
    Ensure that all conditions are met for a user to self-subscribe to the
    Campus. At the moment, these two conditions are:
    - the user's EduPersonPrincipalName attribute value mustn't appear in the
    Campus LDAP base
    - the user's institution or research unit should appear as registered
    structures in the Campus LDAP base
    """
    def wrapped(request, *args, **kwargs):
        if not request.session.get('mellon_session'):
            return redirect(reverse('auth_login') + '?next='+request.path)
        user_data = saml_collect_data(request)

        if ldap_contains_user(user_data):
            return render_message(request, MSG_USER_REGISTERED)

        etablissements = [code for code, _ in ldap_get_code_etablissements()]
        try:
            etablissements.remove(None) # remove extra null entry
        except:
            pass
        if user_data.get('s_etablissement') in etablissements:
            return function(request, *args, **kwargs)
        return render_message(request, MSG_STRUCT_NOT_IN_CAMPUS)
    return wrapped
