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

from account.models import Profile

class SignupForm(forms.ModelForm):
    email = forms.EmailField(required=True)
    name = forms.CharField()
    country = forms.CharField()

    class Meta:
        model = User
        fields = ['username', 'email']

    def __init__(self, *args, **kwargs):
        # Update initial data
        # We expect username with "nickname" key
        # This key (and others) are generated by
        # openid Sreg/AX extensions processor
        initial = kwargs.setdefault('initial', {})
        initial['username'] = initial.get('nickname', '')
        initial['name'] = initial.get('fullname', '')
        super(SignupForm, self).__init__(*args, **kwargs)

    def clean_username(self):
        username = self.cleaned_data['username']
        try:
            User.objects.get(username=username)
        except User.DoesNotExist:
            return username
        else:
            raise forms.ValidationError('This username is already registered')

    def clean_email(self):
        email = self.cleaned_data['email']
        try:
            User.objects.get(email=email)
        except User.DoesNotExist:
            return email
        else:
            raise forms.ValidationError('This email is already registered')


    def save(self, *args, **kwargs):
        user = super(SignupForm, self).save(*args, **kwargs)
        profile = Profile()
        profile.country = self.cleaned_data['country']
        profile.name = self.cleaned_data['name']
        profile.user = user
        profile.save()
        return user
