from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import Permission
from django.forms.util import ErrorList
from django.utils.translation import gettext as _
from ldt.management import get_content_type_list
from models import ldt, IriGroup


class ldtForm(UserCreationForm):
        
    class Meta:
        model = ldt
        
    def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None,
                 initial=None, error_class=ErrorList, label_suffix=':',
                 empty_permitted=False, instance=None):
                 
        if instance:
            initial = initial or {}           
        
        super(ldtForm, self).__init__(data, files, auto_id, prefix,
            initial, error_class, label_suffix, empty_permitted, instance)
            
        # filtre les permissions necessaires
        content_type_list = get_content_type_list()
        self.fields['user_permissions'].queryset = Permission.objects.filter(content_type__in=content_type_list)
        
        if instance:
            self.fields['password1'].required = False
            self.fields['password1'].label = _('New password')
            self.fields['password2'].required = False
            self.fields['password2'].label = _('New password confirmation')
        
        self._password_change = True
        
    def clean_username(self):
        if self.instance:
            return self.cleaned_data['username']
        return super(ldtForm, self).clean_username()
    
    def clean_password2(self): 
        if self.instance and self.cleaned_data['password1'] == '' and self.cleaned_data['password2'] == '':
            self._password_change = False
            return u''
        return super(ldtForm, self).clean_password2()
    
   
    def save(self, commit=True):
        Super = self._password_change and ldtForm  or UserCreationForm  
        user = super(Super, self).save(commit=False)
        # if user.pk != None:
            # self.save_m2m()
        
        if commit:
            user.save()
        
        return user
        
class IriGroupForm(forms.ModelForm):
    class meta:
        model = IriGroup
        
    def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None,
                 initial=None, error_class=ErrorList, label_suffix=':',
                 empty_permitted=False, instance=None):
        if instance:
            initial = initial or {}                               
        
        super(IriGroupForm, self).__init__(data, files, auto_id, prefix,
            initial, error_class, label_suffix, empty_permitted, instance)
            
        # filtre les permissions necessaires
        content_type_list = get_content_type_list()
        self.fields['permissions'].queryset = Permission.objects.filter(content_type__in=content_type_list)
        
class EmailChangeForm(forms.Form):
    email1 = forms.EmailField(label=_("E-mail"), max_length=75)
    email2 = forms.EmailField(label=_("E-mail"), max_length=75)
    
    def __init__(self, user=None, *args, **kwargs):
        self.user = user
        super(EmailChangeForm, self).__init__(*args, **kwargs)
        
    def clean_email2(self):
        email1 = self.cleaned_data.get('email1')
        email2 = self.cleaned_data.get('email2')
        if email1 and email2:
            if email1 != email2:
                raise forms.ValidationError(_("The two emails didn't match."))
        return email2

    
    def save(self):
        self.user.email = self.cleaned_data['email1']
        self.user.save()
        return self.user

