import logging
from django.views.generic import FormView
from django.utils.translation import ugettext_lazy as _, ugettext as ugt

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



MSG_WCS_POST = _("""Your account creation request has been sent.  An
                    email summing up your request has just been sent to you. It
                    contains all the information needed for you to follow up
                    with the account creation process.""")

MSG_USERNONE =  _("""Your account has already been registered to the Campus
                     Condorcet account base.""")

wcs_fields = [
    'prenom', 'nom', 'email', 'ep_principal_name', 's_etablissement',
    'ep_primary_affiliation', 's_entite_affectation_principale', 's_emp_corps',
    's_liste_rouge', 'hote_etablissement', 'hote_unite', 'hote_commentaire']

wcs_multiple_fields = ['s_entite_affectation', 'ep_affiliation']


logger = logging.getLogger('django')


def wcs_post(request):
    logger.info(u'Processing request %s' % request)
    return render_message(request, MSG_WCS_POST)

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

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

        if self.request.session.get('tracking_code'):
            initial.update(initial_from_tracking_code(
                    self.request.session['tracking_code']))
            message = initial['message'] if initial.get('message') else ''

            initial['user_help_msg'] = \
                    _("""%s %s sent an invite with the following invitation
                    message:\n
                    "%s"\n
                    Please check the entries below, fill in the empty fields
                    and submit your account request.\n""") % (
                             initial.get('hote_prenom'),
                             initial.get('hote_nom'),
                             message)
        else:
            initial['user_help_msg'] = _("Please fill in the empty fields and "
                                         "submit your account request")

        if 'mellon_session' in self.request.session:
            data = self.request.session['mellon_session']
            for attribute in sso_attributes:
                if data.get(attribute):
                    attribute_element = data.get(attribute)[0]
                    initial[attribute] = attribute_element
            initial['user_nickname'] = craft_user_nickname(data)
            if data.get('s_etablissement', [None])[0]:
                self.request.session['code_etablissement'] = data.get('s_etablissement')[0]
                initial['s_etablissement'] = ldap_get_description_etablissements(
                        data.get('s_etablissement')[0]) or data.get('s_etablissement')[0]
        initial['yet_member'] = False
        return initial

    def form_valid(self, form):
        pocform = 'traitement_supann'
        wcs = 'http://forms-condorcet.dev.entrouvert.org/'
        posturl = wcs+'/api/formdefs/'+pocform+'/submit'

        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 render_message(self.request, MSG_USERNONE)
        else:
            delimiter = ','
            wcs_rest_data = {}

            for field in wcs_fields:
                sanitized_form_entry = 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',''))

            if self.request.session.get('code_etablissement'):
                wcs_rest_data['s_etablissement'] = self.request.session['code_etablissement']
            if post_dict.get('hote_etablissement', '') != '':
                code_etablissement = post_dict['hote_etablissement']
                wcs_rest_data['hote_etablissement'] = ldap_get_description_etablissements(code_etablissement)
                wcs_rest_data['hote_etablissement_raw'] = code_etablissement

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