from django.core.management.base import BaseCommand

from establishment.models import Establishment
from transfer.models import EstablishmentAssets


class Command(BaseCommand):
    help = 'Add preview_image_url values from old db to new db'

    def handle(self, *args, **kwargs):
        count = 0
        url = 'https://1dc3f33f6d-3.optimicdn.com/gaultmillau.com/'
        raw_qs = EstablishmentAssets.objects.raw(
            '''SELECT establishment_assets.id, establishment_id, attachment_suffix_url
               FROM establishment_assets
               WHERE attachment_file_name IS NOT NULL
                 AND attachment_suffix_url IS NOT NULL
                 AND scope = 'public'
                 AND type = 'Photo'
                 AND menu_id IS NULL
               GROUP BY establishment_assets.id, establishment_id, attachment_suffix_url;'''
        )
        queryset = [vars(query) for query in raw_qs]
        for obj in queryset:
            establishment = Establishment.objects.filter(old_id=obj['establishment_id'],  image_url__isnull=True).first()
            if establishment:
                img = url + obj['attachment_suffix_url']
                img_url = img[:-12]
                extension = img.split('.')[-1:][0]  # JPG
                establishment.preview_image_url = f'{img_url}xlarge.{extension}'
                establishment.image_url = img
                establishment.save()
                count += 1
        self.stdout.write(self.style.WARNING(f'Updated {count} objects.'))
