from django.contrib.auth.models import *

from django.forms import ModelForm
from django import forms

def _get_corrected_permissions():
    perms = Permission.objects.all()
    perms = perms.exclude(codename__startswith='add_')
    perms = perms.exclude(codename__startswith='change_')
    perms = perms.exclude(codename__startswith='delete_')
    return perms


class GroupForm(ModelForm):

    class Meta:
        model = Group
        fields = ('name','permissions')

    permissions = forms.ModelMultipleChoiceField(_get_corrected_permissions())

class UserForm(ModelForm):

    def __init__(self,*args,**kwargs):
        super(UserForm,self).__init__(*args,**kwargs)
        self.fields['email'].required = True
        self.fields['groups'].help_text = 'The groups this user belongs to. A user will get all permissions granted to each of his/her group.'
        self.fields['is_superuser'].label = 'Give this user all permissions regardless of groups'
        self.fields['is_superuser'].help_text = ''

    class Meta:
        model = User
        fields = ('email','first_name','last_name','groups','is_superuser')

    def clean_email(self):
        email = self.cleaned_data.get('email')
        if email:
            users = User.objects.filter(email=email).exclude(email=self.instance.email)
            if users:
                raise forms.ValidationError(u'Sorry A User with this Email Address already exists')

        return email


class UserPasswordForm(forms.Form):

    password1 = forms.CharField(widget=forms.PasswordInput(), min_length=6, max_length=20, label='Password', help_text='')
    password2 = forms.CharField(widget=forms.PasswordInput(), min_length=6, max_length=20, label='Confirm Password')

    def clean_password2(self):
        password1 = self.cleaned_data.get('password1')
        password2 = self.cleaned_data.get('password2')

        if password1 and password2:
            if password1 != password2:
                raise forms.ValidationError(u'Please ensure your passwords match')
