from django.utils.translation import ugettext_lazy as _
from django import forms
from .utils import ldap_get_unites, ldap_get_etablissements, sso_attributes, \
    sso_select_attributes, sso_tupled_attributes, \
    sso_strict_readonly_attributes, sso_needed_description_attributes, \
    ldap_get_description_etablissements, ldap_get_description_unites


AFFILIATION_CHOICES = (
    ('researcher', _('Researcher')),
    ('teacher', _('Teacher')),
    ('emeritus', _('Emeritus')),
    ('student', _('Student')),
    ('staff', _('Staff')),
    ('registered-reader', _('Registered-reader')),
)

AFFECTATION_CHOICES = (
    ('B', 'Bleue'),
    ('V', 'Verte'),
    ('J', 'Jaune'),
    ('N', 'Noire'),
    ('R', 'Rouge'),
)

EMP_CORPS_CHOICES = (
('', '------------'),
('{NCORPS}056', "ADJ. ADM DE L'EN ET DE L'ENS SUP"),
('{NCORPS}837', 'ADJOINT TECHNIQUE DE RECH.ET FORMATION'),
('{NCORPS}839', 'ADJOINT TECHNIQUE-RECHERCHE & FORMATION'),
('{NCORPS}278', 'ADJOINT TECHNIQUE ( RECHERCHE CNRS)'),
('{NCORPS}305', "ASSISTANT DE L'ENSEIGNEMENT SUPERIEUR"),
('{NCORPS}275', 'ASSISTANT INGENIEUR ( RECHERCHE CNRS)'),
('{NCORPS}051', "ATTACHE D'ADMINISTRATION DE L'ETAT"),
('{NCORPS}562', "CHARGE D'ENSEIGNEMENT HORS EPS"),
('{NCORPS}355', "DIR. D'ETUDES EPHE ENC EFEO"),
('{NCORPS}276', "INGENIEUR D'ETUDES(RECHERCHE CNRS)"),
('{NCORPS}835', "INGENIEUR D'ETUDES  (RECH ET FORM)"),
('{NCORPS}836', 'INGENIEUR DE RECHERCHE (RECH ET FORM)'),
('{NCORPS}277', 'INGENIEUR DE RECHERCHE (RECHERCHE CNRS)'),
('{NCORPS}301', 'MAITRE DE CONFERENCES DES UNIVERSITES'),
('{NCORPS}311', 'MAITRE DE CONF PRATICIEN HOSPITALIER '),
('{NCORPS}310', 'PROF DES UNIV.- PRATICIEN HOSPITALIER'),
('{NCORPS}551', 'PROFESSEUR AGREGE'),
('{NCORPS}553', 'PROFESSEUR CERTIFIE'),
('{NCORPS}300', 'PROFESSEUR DES UNIVERSITES'),
('{NCORPS}054', 'SECRETAIRE ADMINISTRATIF'),
('{NCORPS}279', 'TECHNICIEN ( RECHERCHE CNRS)'),
('{NCORPS}830', 'TECHNICIEN DE RECHERCHE & FORMATION(NES)'),
('{NCORPS}841', 'TECHNIQUE CONTRACTUEL CNRS')
)


ETABLISSEMENT_CHOICES = ()

UNITE_CHOICES = ()

class RegistrationForm(forms.Form):
    """
    Main registration form when requesting access to the Campus.

    User data may be fetched for a single sign-on (SSO) procedure and used to
    pre-fill the fields. Pre-filled fields are also set as readonly to ensure 
    that the data fetched from the SSO process and sent to w.c.s. is genuine.
    """
    user_help_msg = ''
    user_nickname = ''

    def __init__(self, *args, **kwargs):
        super(RegistrationForm, self).__init__(*args, **kwargs)
        self.user_nickname = kwargs['initial'].get('user_nickname', '')
        self.user_help_msg = kwargs['initial'].get('user_help_msg', '')

        for field in sso_attributes:
            if  kwargs['initial'].get(field,'') != '':
                if field in sso_select_attributes:
                    simple_choice = '%s' % kwargs['initial'][field]
                    self.fields[field].choices = ((simple_choice, (simple_choice)),)

                if field in sso_tupled_attributes.keys():
                    simple_choice = '%s' % kwargs['initial'][field]
                    backend_dict = dict(globals().get(sso_tupled_attributes[field], {}))
                    if backend_dict.get(simple_choice):
                        self.fields[field].choices = ((simple_choice,
                                backend_dict.get(simple_choice)),)
                self.fields[field].widget.attrs['readonly'] = True

            if field in sso_strict_readonly_attributes:
                self.fields[field].widget.attrs['readonly'] = True

        if kwargs['initial'].get('yet_member', '') is False:
            extra_affiliation = (('affiliate', 'affiliate'),)
        else:
            extra_affiliation = (('member', 'member'),)
        self.fields['ep_affiliation'].choices = extra_affiliation
        self.fields['ep_affiliation'].widget.attrs['readonly'] = True

        code_etablissement =  kwargs['initial'].get('s_etablissement', '')
        if code_etablissement != '':
            self.fields['s_etablissement_description'].initial = ldap_get_description_etablissements(code_etablissement)
            self.fields['s_etablissement_description'].widget.attrs['readonly'] = True
        code_unite =  kwargs['initial'].get('s_entite_affectation_principale', '')
        if code_unite != '':
            self.fields['s_entite_affectation_principale_description'].initial = ldap_get_description_unites(code_unite)
        #User shouldn't be able to define this field
        self.fields['s_entite_affectation_principale_description'].widget.attrs['readonly'] = True

        code_hote_etablissement =  kwargs['initial'].get('hote_etablissement', '')
        if code_hote_etablissement != '':
            self.fields['hote_etablissement'].choices = ((code_hote_etablissement, ldap_get_description_etablissements(code_hote_etablissement)),)
            self.fields['hote_etablissement'].widget.attrs['readonly'] = True
            self.fields['hote_unite'].widget.attrs['readonly'] = True
        code_hote_unite =  kwargs['initial'].get('hote_unite', '')
        if code_hote_unite != '':
            self.fields['hote_unite'].choices = ((code_hote_unite, ldap_get_description_unites(code_hote_unite)),)
        #User shouldn't be able to define this field
            self.fields['hote_unite'].widget.attrs['readonly'] = True
            self.fields['hote_etablissement'].widget.attrs['readonly'] = True

        affiliation = kwargs['initial'].get('ep_primary_affiliation')
        if affiliation:
            for engstr, transstr in AFFILIATION_CHOICES:
                if engstr == affiliation:
                    self.fields['ep_primary_affiliation'].choices = ((engstr, transstr),)
                    break


    nom = forms.CharField(max_length=100, label=_("Last name"))
    prenom = forms.CharField(max_length=100, label=_("First name"))
    email = forms.CharField(max_length=100, label=_("Email address"))

    # Attributes from the Internet2 eduPerson and RENATER SupAnn2009 specs.
    #  ep_* -> eduPerson attributes:
    ep_principal_name = forms.CharField(
        required=False,
        max_length=100,
        label="eduPersonPrincipalName"
    )
    # eduPersonPrimaryAffiliation
    ep_primary_affiliation = forms.ChoiceField(
        required=False,
        choices=AFFILIATION_CHOICES,
        label=_("Affiliation")
    )
    # eduPersonPrimaryAffiliation
    ep_affiliation = forms.MultipleChoiceField(
        required=False, choices=AFFILIATION_CHOICES, label=_("Extra affiliations"))

    # s_* -> supannPerson attributes:
    # supannEtablissement
    s_etablissement  = forms.CharField(
        required=False, max_length=100, label=_("Institution"))
    s_etablissement_description  = forms.CharField(
        required=False, max_length=100, label=_("Institution"))
    #invite_unite  = forms.CharField(
    #    required=False, label=_("Research entity or unit"), initial='')
    # supannEntiteAffectationPrincipale
    s_entite_affectation_principale = forms.CharField(
        required=False, label=_("Unit"), initial='')
    s_entite_affectation_principale_description = forms.CharField(
        required=False, label=_("Unit"), initial='')
    # supannEntiteAffectation
    s_entite_affectation = forms.CharField(
        required=False, max_length=100, label=_("Assignment units"))
    # supannEmpCorps
    s_emp_corps = forms.ChoiceField(
        choices=EMP_CORPS_CHOICES, required=False, label=_("Source entity"))
    # supannListeRouge
    s_liste_rouge = forms.BooleanField(
        initial=True, required=False, label=_("Unlist contact information"))

    # hote_* -> host attributes:
    hote_etablissement  = forms.ChoiceField(
        required=False, choices=ldap_get_etablissements(),
        label=_("Institution"), initial=None)
    hote_unite  = forms.ChoiceField(
        required=False, choices=ldap_get_unites(),
        label=_("Research entity or unit"), initial=None)
    hote_etablissement_description  = forms.ChoiceField(
        required=False, choices=ldap_get_etablissements(),
        label=_("Institution"), initial=None)
    hote_unite_description  = forms.ChoiceField(
        required=False, choices=ldap_get_unites(),
        label=_("Research entity or unit"), initial=None)
    hote_commentaire = forms.CharField(
        widget=forms.Textarea(), max_length=999,
        label=_("Comments to your host"), required=False)

    class Meta:
        widgets= {'form' : forms.HiddenInput()}
