# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django import forms
from django.contrib.auth.forms import PasswordResetForm, ReadOnlyPasswordHashField

from coin.members.models import Member


class MemberCreationForm(forms.ModelForm):

    """
    This form was inspired from django.contrib.auth.forms.UserCreationForm
    and adapted to coin specificities
    """
    username = forms.RegexField(required=False,
                                label="Nom d'utilisateur", max_length=30, regex=r"^[\w.@+-]+$",
                                help_text="Laisser vide pour le générer automatiquement à partir du "
                                "nom et du prénom")
    password = forms.CharField(
        required=False, label='Mot de passe', widget=forms.PasswordInput)

    class Meta:
        model = Member
        fields = '__all__'

    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()
        return member


class MemberChangeForm(forms.ModelForm):

    """
    This form was inspired from django.contrib.auth.forms.UserChangeForm
    and adapted to coin specificities
    """
    password = ReadOnlyPasswordHashField()

    class Meta:
        model = Member
        fields = '__all__'

    def __init__(self, *args, **kwargs):
        super(MemberChangeForm, self).__init__(*args, **kwargs)
        f = self.fields.get('user_permissions', None)
        if f is not None:
            f.queryset = f.queryset.select_related('content_type')

    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"]

    def clean_username(self):
        # idem clean_password
        return self.initial["username"]


class MemberPasswordResetForm(PasswordResetForm):
    pass
