from django import forms
from django.contrib.auth.models import User
from .models import Profile


class ProfileForm(forms.ModelForm):
    first_name = forms.CharField(required=False, max_length=30)
    last_name = forms.CharField(required=False, max_length=150)
    email = forms.EmailField(required=False)

    class Meta:
        model = Profile
        fields = ['image', 'bio']

    def save(self, commit=True):
        profile = super().save(commit=False)
        # update related user fields
        user = profile.user
        user.first_name = self.cleaned_data.get('first_name', user.first_name)
        user.last_name = self.cleaned_data.get('last_name', user.last_name)
        email = self.cleaned_data.get('email')
        if email:
            user.email = email
        if commit:
            user.save()
            profile.save()
        return profile
