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

from collection.models import Collection
from utils.methods import image_url_valid, get_image_meta_by_url


class Command(BaseCommand):
    SORL_THUMBNAIL_ALIAS = 'collection_image'

    def handle(self, *args, **options):
        max_size = 1048576

        with transaction.atomic():
            for collection in Collection.objects.all():
                if not image_url_valid(collection.image_url):
                    continue

                size, width, height = get_image_meta_by_url(collection.image_url)

                if size < max_size:
                    self.stdout.write(self.style.SUCCESS(f'No need to compress images size is {size / (2 ** 20)}Mb\n'))
                    continue

                percents = round(max_size / (size * 0.01))
                width = round(width * percents / 100)
                height = round(height * percents / 100)
                collection.image_url = get_thumbnail(
                    file_=collection.image_url,
                    geometry_string=f'{width}x{height}',
                    upscale=False
                ).url

                collection.save()
