from django import forms
from django.conf import settings
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from django.contrib.auth.models import User
from django.forms.util import ErrorList
from django.utils.translation import gettext as _
from ldt.user.models import get_or_create_profile
from models import Ldt


class LdtForm(UserCreationForm):
        
    class Meta:
        model = Ldt
        
    def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None,
                 initial=None, error_class=ErrorList, label_suffix=':',
                 empty_permitted=False, instance=None):
                 
        if instance:
            initial = initial or {}           
        
        super(LdtForm, self).__init__(data, files, auto_id, prefix,
            initial, error_class, label_suffix, empty_permitted, instance)
        
        if instance:
            self.fields['password1'].required = False
            self.fields['password1'].label = _('New password')
            self.fields['password2'].required = False
            self.fields['password2'].label = _('New password confirmation')
        
        self._password_change = True
        
    def clean_username(self):
        if self.instance:
            return self.cleaned_data['username']
        return super(LdtForm, self).clean_username()
    
    def clean_password2(self): 
        if self.instance and self.cleaned_data['password1'] == '' and self.cleaned_data['password2'] == '':
            self._password_change = False
            return u''
        return super(LdtForm, self).clean_password2()
    
   
    def save(self, commit=True):
        Super = self._password_change and LdtForm  or UserCreationForm  
        user = super(Super, self).save(commit=False)
        # if user.pk != None:
            # self.save_m2m()
        
        if commit:
            user.save()
        
        return user

        
class EmailChangeForm(forms.Form):
    email1 = forms.EmailField(label=_("E-mail"), max_length=75)
    email2 = forms.EmailField(label=_("E-mail"), max_length=75)
    
    def __init__(self, user=None, *args, **kwargs):
        self.user = user
        super(EmailChangeForm, self).__init__(*args, **kwargs)
        
    def clean_email2(self):
        email1 = self.cleaned_data.get('email1')
        email2 = self.cleaned_data.get('email2')
        if email1 and email2:
            if email1 != email2:
                raise forms.ValidationError(_("The two emails didn't match."))
        return email2

    
    def save(self):
        self.user.email = self.cleaned_data['email1']
        self.user.save()
        return self.user
    

class NameChangeForm(forms.Form):
    first_name = forms.CharField(label=_("First name"), max_length=30)
    last_name = forms.CharField(label=_("Last name"), max_length=30)
    
    def __init__(self, user=None, *args, **kwargs):
        self.user = user
        super(NameChangeForm, self).__init__(*args, **kwargs)
        
        
    def save(self):
        self.user.first_name = self.cleaned_data['first_name']
        self.user.last_name = self.cleaned_data['last_name']
        self.user.save()
        return self.user
    

class ProfileForm(UserChangeForm):
    
    def __init__(self, user=None, *args, **kwargs):
        #self.user = user
        super(ProfileForm, self).__init__(*args, **kwargs)
        
 
    class Meta:
        model = User
        fields = ('username', 'email', 'first_name', 'last_name')
        
        
class LanguageChangeForm(forms.Form):
    language = forms.ChoiceField(label=_("Language"), choices=settings.LANGUAGES)
    
    def __init__(self, user=None, *args, **kwargs):
        self.user = user
        super(LanguageChangeForm, self).__init__(*args, **kwargs)
        
    def save(self):
        profile = get_or_create_profile(self.user)
        profile.language = self.cleaned_data['language']
        profile.save()
        return self.user
    
        