import logging
from django.views.generic import FormView
from django.shortcuts import render
from django.utils.translation import ugettext as _

from .forms import RegistrationForm
from .utils import ldap_contains_user, wcs_submit, \
                   sso_attributes, craft_user_nickname, \
                   generate_eppn

logger = logging.getLogger('django')

# TODOs
#   export global config variables in settings.py

# Create your views here.
wcs_fields = ['prenom',
              'nom',
              'email',
              'ep_principal_name',
              's_etablissement',
              'ep_primary_affiliation',
              's_entite_affectation_principale',
              's_emp_corps',
              's_liste_rouge',
              'hote_prenom',
              'hote_nom',
              'hote_etablissement',
              'hote_unite']

wcs_multiple_fields = ['s_entite_affectation',
                       'ep_affiliation']

def usernone(request):
    logger.info(u'User %s already registered to the LDAP user branch.', request.user)
    message = _("Your account has already been registered to the Campus Condorcet account base.")
    template = 'simple_message.html'
    return render(request, template, {'message' : message})

def wcs_post(request):
    logger.info(u'Processing request %s',  request)
    return render(request, 'simple_message.html',
            {'message':_("Your account creation request has been sent.")})

class RegistrationFormView(FormView):
    form_class = RegistrationForm
    template_name = 'registration_form.html'
    success_url = '/register/wcs_post' # Mandatory?

    def get_initial(self):
        initial = super(RegistrationFormView, self).get_initial()

        if 'mellon_session' in self.request.session:
            for attribute in sso_attributes:
                attribute_element = self.request.session['mellon_session'].get(attribute, [''])[0]
                initial[attribute] = str(attribute_element)
            initial['user_nickname'] = craft_user_nickname(self.request.session['mellon_session'])
            initial['user_help_msg'] = _("Please check the entries below, fill in the empty fields and submit your account request")
        else:
            initial['user_help_msg'] = _("Please fill in the empty fields and submit your account request")

        return initial

    def form_valid(self, form):
        post_dict = self.request.POST
        form_adequate_data = {}
        form_adequate_data['ep_principal_name'] = post_dict.get('ep_principal_name')

        if form_adequate_data['ep_principal_name'] and ldap_contains_user(form_adequate_data):
            return usernone(self.request)
        else:
            delimiter = ','
            wcs_rest_data = {}

            for field in wcs_fields:
                sanitized_form_entry = str(post_dict.get(field, False))
                wcs_rest_data[field] = sanitized_form_entry

            for multiple_field in wcs_multiple_fields:
                sanizted_form_list = post_dict.getlist(multiple_field, [])
                wcs_rest_data[multiple_field] = delimiter.join(sanizted_form_list)

            if post_dict.get('ep_principal_name', '') == '':
                wcs_rest_data['ep_principal_name'] = generate_eppn(post_dict.get('nom',''))

            wcs_submit(wcs_rest_data)
            return super(RegistrationFormView, self).form_valid(form)
