from sorl.thumbnail import default as sorl_thumbnail

from wagtail.admin.widgets.chooser import BaseChooser


class BaseChooserWithImage(BaseChooser):
    def get_image(self, instance):
        return instance.image

    def get_value_data_from_instance(self, instance):
        data = super().get_value_data_from_instance(instance)
        data.update(
            {
                "preview": self.get_primary_image_preview(instance),
            }
        )
        return data

    def get_value_data(self, value):
        if not value:
            value = None

        return super().get_value_data(value)

    def get_primary_image_preview(self, instance):
        image = self.get_image(instance)

        if image:
            thumb = sorl_thumbnail.backend.get_thumbnail(
                image,
                "165x165",
                upscale=False,
                format="JPEG",
            )
            return {
                "url": thumb.url,
                "width": thumb.width,
                "height": thumb.height,
                "alt": instance.description,
            }

        return {}


class BaseProductChooser(BaseChooserWithImage):
    def get_image(self, instance):
        image = instance.primary_image()
        return image.original if hasattr(image, "original") else image["original"]
