from os import path
from StringIO import StringIO
from PIL import Image as PILImage

from django.core.files.base import ContentFile
from django.db.models.signals import post_save
from django.dispatch import receiver

from fiber.models import Image


@receiver(post_save, sender=Image)
def resize_as_a_new_fiber_image(*args, **kwargs):
    im = kwargs.get("instance", None)
    max_width = 450
    max_height = 300
    if im.image.width > max_width or im.image.height > max_height:
        size =  (max_width, max_height)
        image = PILImage.open(im.image.path)
        xxx, image_name = path.split(im.image.path)
        if "." in image_name:
            image_name, extenstion = image_name.rsplit('.', 1)
            name = "%s_cropped.%s" % (image_name, extenstion)
        else:
            name = "%s_cropped" % image_name
        format = image.format
        if image.mode not in ("L", "RGB"):
            image = image.convert("RGB")
        resized_image = image.copy()
        resized_image.thumbnail(size, PILImage.ANTIALIAS)
        fp = StringIO()
        resized_image.save(fp, format, quality=128)
        cf = ContentFile(fp.getvalue())
        fiber_image = Image(title=im.title)
        fiber_image.image.save(name=name, content=cf, save=False)
        fiber_image.save()