import os

from django.conf import settings
from django.core.management.base import BaseCommand
from django.db import transaction
from sorl.thumbnail import get_thumbnail

from establishment.models import Establishment
from utils.methods import image_url_valid, get_image_meta_by_url


class Command(BaseCommand):
    SORL_THUMBNAIL_ALIAS = 'establishment_collection_image'

    def handle(self, *args, **options):
        with transaction.atomic():
            for establishment in Establishment.objects.all():
                if establishment.preview_image_url is None \
                        or not image_url_valid(establishment.preview_image_url):
                    continue
                _, width, height = get_image_meta_by_url(establishment.preview_image_url)
                sorl_settings = settings.SORL_THUMBNAIL_ALIASES[self.SORL_THUMBNAIL_ALIAS]
                sorl_width_height = sorl_settings['geometry_string'].split('x')

                if int(sorl_width_height[0]) > width or int(sorl_width_height[1]) > height:
                    _, file_ext = os.path.splitext(establishment.preview_image_url)

                    self.stdout.write(self.style.SUCCESS(f'Optimize: {establishment.preview_image_url}, extension: {file_ext}'))

                    establishment.preview_image_url = get_thumbnail(
                        file_=establishment.preview_image_url,
                        **sorl_settings,
                        format='JPEG' if file_ext[1:] == 'jpg' else 'PNG'
                    ).url
                    establishment.save()
