from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.forms.util import ErrorList
from django.utils.translation import gettext as _
from models import Ldt

from django.contrib.auth.models import User



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 ProfileChangeForm(forms.Form):
    first_name = forms.CharField(label=_("First name"), max_length=30)
    last_name = forms.CharField(label=_("Last name"), max_length=30)
    email1 = forms.EmailField(label=_("E-mail"), max_length=75)
    email2 = forms.EmailField(label=_("E-mail"), max_length=75)
    username = forms.RegexField(label=_("Username"), max_length=30, regex=r'^[\w.@+-]+$')
    
    def __init__(self, user=None, *args, **kwargs):
        self.user = user
        super(ProfileChangeForm, 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 clean_username(self):
        retrieved_username = '%s' % self.cleaned_data.get('username')
        if retrieved_username != self.user.username and (len(User.objects.filter(username=retrieved_username)) > 0):
            raise forms.ValidationError(_("username %s is already used." % retrieved_username))
        return retrieved_username
    
    def clean_first_name(self):
        first_name = self.cleaned_data.get('first_name')
        if not self.isValidName(first_name):
            raise forms.ValidationError(_("Please use only letter, blanks, or dashes."))
        return first_name
        
    def clean_last_name(self):
        last_name = self.cleaned_data.get('last_name')
        if not self.isValidName(last_name):
            raise forms.ValidationError(_("Please use only letter, blanks, or dashes."))
        return last_name
    
    def isValidName(self, string):
        for i in string:
            if not i.isalpha() and not i in [' ','-']:
                return False
        return True    
    
    
    def save(self):
        self.user.email = self.cleaned_data['email1']
        self.user.first_name = self.cleaned_data['first_name']
        self.user.last_name = self.cleaned_data['last_name']
        self.user.username = self.cleaned_data['username']
        self.user.save()
        return self.user
    