# -*- encoding: utf-8 -*-

from django import forms
from django.conf import settings
import datetime
import pfusers

class ConfirmForm(forms.Form):
    pass

class UploadFileForm(forms.Form):
    file = forms.FileField(label=u"Fichier", required=True)

class UserForm(forms.Form):
    name = forms.RegexField(label=u"Nom d'utilisateur (login)", regex='^[a-z0-9\.\-_]+$', min_length=3, max_length=16, required=True,
            widget=forms.TextInput(attrs={'readonly': True, 'size':'16', 'autocomplete':'off', 'class':'span2'}))
    disabled = forms.BooleanField(label=u'Désactivé',required=False)
    password = forms.CharField(label=u"Nouveau mot de passe", min_length=3, max_length=64, required=False, 
            widget=forms.PasswordInput(attrs={'size':'32', 'autocomplete':'off', 'class':'span3'}))
    password2 = forms.CharField(label=u"Mot de passe (vérification)", min_length=3, max_length=64, required=False,
            widget=forms.PasswordInput(attrs={'size':'32', 'autocomplete':'off', 'class':'span3'}))
    expires = forms.DateField(label=u"Date d'expiration", required=False,
            widget=forms.TextInput(attrs={'size':'16', 'class':'span2 datepicker'}))
    descr = forms.CharField(label=u'Description (nom long)', max_length=256, required=False,
            widget=forms.TextInput(attrs={'size':'256', 'class':'span6'}))
    multiple = forms.BooleanField(label=u'Connexions multiples autorisées',required=False)

    def is_valid(self):
        valid = super(UserForm, self).is_valid()
        if valid:
            # check passwords
            password = self.cleaned_data.get('password')
            password2 = self.cleaned_data.get('password2')
            if password != password2:
                self.errors['password'] = [u'Les deux mots de passe doivent être identiques']
                valid = False
        return valid

class NewUserForm(UserForm):
    name = forms.RegexField(label=u"Nom d'utilisateur (login)", regex='^[a-z0-9\.\-_]+$', min_length=3, max_length=16, required=True,
            widget=forms.TextInput(attrs={'size':'16', 'autocomplete':'off', 'class':'span2'}),
            help_text="""Uniquement lettres, chiffres, point, trait d'union et «_».
                         Si création de plusieurs utilisateurs (voir plus bas), leur login sera de la forme login-N.""")
    # password and expire fields
    password = forms.CharField(label=u"Mot de passe", min_length=3, max_length=64, required=False,
            help_text="""Si vous n'indiquez pas de mot de passe, un mot de passe aléatoire sera
            attribué à chaque utilisateur""",
            widget=forms.PasswordInput(attrs={'size':'32', 'autocomplete':'off', 'class':'span3'}))
    expires = forms.DateField(label=u"Date d'expiration", required=(settings.IDP_UA_MAX_EXPIRES > 0),
            widget=forms.TextInput(attrs={'size':'16', 'class':'span2 datepicker'}))
    userset_number = forms.IntegerField(label=u"Nombre d'utilisateur(s) à créer (login-N)",
            widget=forms.TextInput(attrs={'size':'5', 'class':'span1'}),
            required=True, min_value=1)
    userset_start = forms.IntegerField(label=u"""En cas de création de plusieurs utilisateurs (login-N),
            indiquer le premier numéro N""",
            widget=forms.TextInput(attrs={'size':'5', 'class':'span1'}),
            required=True)

    def is_valid(self):
        valid = super(NewUserForm, self).is_valid()
        if valid:
            name = self.cleaned_data.get('name')
            all_pfusers = pfusers.get_all_pfusers()
            userset_number = int(self.cleaned_data.get('userset_number'))
            if userset_number == 1 and all_pfusers.get(name, None) is not None:
                self.errors['name'] = [u'Un utilisateur avec ce login existe déjà.']
                return False
            if userset_number > 1:
                userset_start = int(self.cleaned_data.get('userset_start'))
                for n in range(userset_start, userset_start + userset_number):
                    if all_pfusers.get('%s-%d' % (name, n), None) is not None:
                        self.errors['name'] = [u"L'utilisateur %s-%d existe déjà." % (name, n)]
                        return False
        return valid

