from django import forms
from django.conf import settings
from django.contrib.auth import get_user_model
from django.utils.translation import gettext as _
from django.contrib.auth.models import Group

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