from django import forms
from django.conf import settings
from django.contrib.auth import get_user_model
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from django.contrib.auth.models import Group
from django.forms.util import ErrorList
from django.utils.translation import gettext as _

User = get_user_model()

class LdtForm(UserCreationForm):
        
    class Meta:
        model = User
        
    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', 'password')
        
        
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):
        self.user.language = self.cleaned_data['language']
        self.user.save()
        return self.user
           
class PictureForm(forms.Form):
    image=forms.ImageField(label=_("Profile picture"), required=False)
    url_image=forms.CharField(max_length=1024, required=False)
    
    def __init__(self, model=None, *args, **kwargs):
        self.model = model
        super(PictureForm, self).__init__(*args, **kwargs)
        
    def clean_image(self):
        image = self.cleaned_data['image']
                
        if image and image.size > settings.PROFILE_IMG_MAX_SIZE:
            raise forms.ValidationError(_("Image size is limited to %s" % settings.PROFILE_IMG_MAX_SIZE))
    
        return image
    
    def save(self):
        
        if not self.cleaned_data['image']:
            return None
        
        class_name = self.model.__class__.__name__
        if isinstance(self.model, Group):
            instance_name = "%s" % self.model.id
            img_container = self.model.get_profile()
        if isinstance(self.model, User):
            instance_name = "%s" % self.model.id
            img_container = self.model
        elif class_name == 'Content':
            instance_name = self.model.iri_id
            img_container = self.model
        elif class_name == 'Project':
            instance_name = self.model.ldt_id
            img_container = self.model
            
        # We change the file name and keep the extension.
        filename = self.cleaned_data['image'].name
        ext = filename.split(".")[-1]
        self.cleaned_data['image'].name = instance_name + "." + ext
        # We save the picture with the correct name
        img_container.image = self.cleaned_data['image']
        img_container.save()
        return self.model   
        