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.utils.translation import gettext as _
import os

User = get_user_model()
    
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 AdminUserCreationForm(UserCreationForm):

    class Meta:
        model = User

    def clean_username(self):
        # Since User.username is unique, this check is redundant,
        # but it sets a nicer error message than the ORM. See #13147.
        username = self.cleaned_data["username"]
        try:
            User.objects.get(username=username)
        except User.DoesNotExist:
            return username
        raise forms.ValidationError(self.error_messages['duplicate_username'])    

class AdminUserChangeForm(UserChangeForm):
    language = forms.ChoiceField(label=_("Language"), choices=[(k,_(v)) for k,v in settings.LANGUAGES], initial=settings.LANGUAGE_CODE[:2])
    image = forms.ImageField(label=_("Profile picture"), required=False)    

    def clean_image(self):
        image = self.cleaned_data['image']

        if not image:
            return settings.DEFAULT_USER_ICON

        if image and image.size > settings.PROFILE_IMG_MAX_SIZE:
            raise forms.ValidationError(_("Image size is limited to %s" % settings.PROFILE_IMG_MAX_SIZE))

        if image != self.instance.image:    
            filename = image.name
            ext = filename.split(".")[-1]
            image.name = os.path.join(os.path.dirname(filename),str(self.instance.id) + "." + ext)
        
        return image

    
    class Meta:
        model = User
        
        
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


        