from django.contrib.auth import get_user_model
from django.contrib.auth.forms import PasswordChangeForm
from django import forms

from .models import BIO_MAX_LENGTH, UserProfile


class UsernameForm(forms.ModelForm):
    class Meta:
        model = get_user_model()
        fields = ['username']

    def clean_username(self):
        username = self.cleaned_data['username']
        User = get_user_model()
        if User.objects.exclude(pk=self.instance.pk).filter(username=username).exists():
            raise forms.ValidationError('That username is already taken.')
        return username


class EmailForm(forms.ModelForm):
    email = forms.EmailField(required=False)

    class Meta:
        model = get_user_model()
        fields = ['email']

    def clean_email(self):
        return self.cleaned_data.get('email', '').strip()


class AvatarForm(forms.Form):
    avatar = forms.ImageField(
        label='Profile picture',
        widget=forms.ClearableFileInput(attrs={'accept': 'image/*'}),
    )


class BioForm(forms.ModelForm):
    bio = forms.CharField(
        label='Bio',
        required=False,
        max_length=BIO_MAX_LENGTH,
        widget=forms.Textarea(attrs={
            'rows': 4,
            'placeholder': 'Tell people about yourself…',
            'maxlength': BIO_MAX_LENGTH,
        }),
    )

    class Meta:
        model = UserProfile
        fields = ['bio']
