from django import forms
from django.contrib.admin.widgets import FilteredSelectMultiple
from django.utils.translation import ugettext as _
from accounts.models import CampusUser
from permissions.models import CampusPermission


class CampusUserChangeForm(forms.ModelForm):
    granted_permissions = forms.ModelMultipleChoiceField(
        label=_('Granted permissions'),
        required=False,
        queryset=CampusPermission.objects.all(),
        widget=FilteredSelectMultiple(
            verbose_name=_('permissions'),
            is_stacked=False
        )
    )
    revoked_permissions = forms.ModelMultipleChoiceField(
        label=_('Revoked permissions'),
        required=False,
        queryset=CampusPermission.objects.all(),
        widget=FilteredSelectMultiple(
            verbose_name=_('permissions'),
            is_stacked=False
        )
    )

    class Meta:
        model = CampusUser
        exclude = ('password', )

    def __init__(self, *args, **kwargs):
        # Init form fields for related permissions
        if 'instance' in kwargs:
            initial = kwargs.setdefault('initial', {})
            initial['granted_permissions'] = [p.pk for p in kwargs['instance'].granted_permissions.all()]
            initial['revoked_permissions'] = [p.pk for p in kwargs['instance'].revoked_permissions.all()]

        super(CampusUserChangeForm, self).__init__(*args, **kwargs)

    def save(self, commit=True):
        user = super(CampusUserChangeForm, self).save(commit=False)

        # Prepare a 'save_m2m' method for the form,
        old_save_m2m = self.save_m2m

        def save_m2m():
            old_save_m2m()

            user.granted_permissions.clear()
            for permission in self.cleaned_data['granted_permissions']:
                user.granted_permissions.add(permission)

            user.revoked_permissions.clear()
            for permission in self.cleaned_data['revoked_permissions']:
                user.revoked_permissions.add(permission)

        self.save_m2m = save_m2m

        if commit:
            user.save()
            self.save_m2m()

        return user


class CampusUserCreationForm(forms.ModelForm):
    password1 = forms.CharField(label=_('Password'), widget=forms.PasswordInput)
    password2 = forms.CharField(label=_('Password confirmation'), widget=forms.PasswordInput)

    class Meta:
        model = CampusUser
        fields = ('email', 'last_name', 'first_name', 'middle_name')

    def clean_password2(self):
        # Check that the two password entries match
        password1 = self.cleaned_data.get("password1")
        password2 = self.cleaned_data.get("password2")
        if password1 and password2 and password1 != password2:
            raise forms.ValidationError("Passwords don't match")
        return password2

    def save(self, commit=True):
        # Save the provided password in hashed format
        user = super(CampusUserCreationForm, self).save(commit=False)
        user.set_password(self.cleaned_data["password1"])
        if commit:
            user.save()
        return user