from django import forms
from django.utils.html import format_html
from django.forms.utils import ErrorList

from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm


class BulmaFormErrorList(ErrorList):
    def __str__(self):
        return self.as_p()

    def as_p(self):
        if not self:
            return ''
        return format_html('<p class="help is-danger">{}</p>', *[e for e in self])


class ExtendedUserCreationForm(UserCreationForm):
    email = forms.EmailField(required=True)

    class Meta:
        model = User
        fields = ('username', 'email', 'password1', 'password2')

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.error_class = BulmaFormErrorList
        self.fields['username'].widget.attrs.update(
            {'class': 'input', 'placeholder': 'Your username', 'required': True})
        self.fields['email'].widget.attrs.update(
            {'class': 'input', 'placeholder': 'Your email', 'required': True})
        self.fields['password1'].widget.attrs.update(
            {'class': 'input', 'placeholder': 'Your password', 'required': True})
        self.fields['password2'].widget.attrs.update(
            {'class': 'input', 'placeholder': 'Confirm your password', 'required': True})

    def save(self, commit=True):
        user = super().save(commit=False)
        user.email = self.cleaned_data.get('email')
        if commit:
            user.save()
        return user


class ExtendedAuthenticationForm(AuthenticationForm):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.error_class = BulmaFormErrorList
        self.fields['username'].widget.attrs.update(
            {'class': 'input', 'placeholder': 'Enter your username', 'required': True})
        self.fields['password'].widget.attrs.update(
            {'class': 'input', 'placeholder': 'Enter your password', 'required': True})
