from django.db import models
from django.conf import settings

from PIL import Image


class UserProfile(models.Model):
    user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    photo = models.ImageField(upload_to='users/%Y/%m/%d/',
            blank=True)
    def __str__(self):
        return f'{self.user.username}\'s profile'
    def save(self, *args, **kwargs):
        """ 
        Override the default save function to fix the photo size
        """
        super(UserProfile, self).save(*args, **kwargs)
        if self.photo:
            img = Image.open(self.photo.path)
            # resize the provided thumbnail to (300, 300)
            if img.width > 200 or img.height > 200:
                output_size = (200, 200) # width, height
                img.thumbnail(output_size)
                img.save(self.photo.path)
