# -*- coding: utf-8 -*-
from django import forms
from django.contrib.auth.forms import ReadOnlyPasswordHashField

from coin.members.models import Member


class MemberCreationForm(forms.ModelForm):
    password = forms.CharField(label='Password', widget=forms.PasswordInput)

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

    def save(self, commit=True):
        """
        Save member, then set his password
        """
        member = super(MemberCreationForm, self).save(commit=False)
        member.set_password(self.cleaned_data["password"])
        if commit:
            member.member()
            member.set_ldap_password(self.cleaned_data["password"])
        return member


class MemberChangeForm(forms.ModelForm):
    password = ReadOnlyPasswordHashField()

    class Meta:
        model = Member
        fields = ('password', 'first_name', 'last_name', 'is_active', 'is_staff')

    def clean_password(self):
        # Regardless of what the user provides, return the initial value.
        # This is done here, rather than on the field, because the
        # field does not have access to the initial value
        return self.initial["password"]
