from django.core.management.base import BaseCommand
from tqdm import tqdm
from establishment.models import Establishment
from transfer.models import Reviews, ReviewTexts


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

    def handle(self, *args, **kwargs):
        count = 0
        update_locale = 0
        valid_reviews = {}

        queryset = Reviews.objects.exclude(
            establishment_id__isnull=True
        ).filter(
            aasm_state='published'
        ).values_list(
            'id',
            'establishment_id',
            'updated_at',
        )

        for r_id, establishment_id, new_date in tqdm(queryset):
            try:
                review_id, date = valid_reviews[establishment_id]
            except KeyError:
                valid_reviews[establishment_id] = (r_id, new_date)
            else:
                if new_date > date:
                    valid_reviews[establishment_id] = (r_id, new_date)

        text_qs = ReviewTexts.objects.exclude(
            locale__isnull=True
        ).filter(
            review_id__in=(value[0] for value in valid_reviews.values()),
        ).values_list(
            'review__establishment_id',
            'locale',
            'text',
        )

        for es_id, locale, text in tqdm(text_qs):
            establishment = Establishment.objects.filter(old_id=es_id).first()
            if establishment:
                description = establishment.description
                description.update({
                    locale: text
                })
                establishment.description = description
                establishment.save()
                count += 1

        # Если нет en-GB в поле
        for establishment in tqdm(Establishment.objects.filter(old_id__isnull=False)):
            description = establishment.description
            if len(description) and 'en-GB' not in description:
                description.update({
                    'en-GB': next(iter(description.values()))
                })
                establishment.description = description
                establishment.save()
                update_locale += 1

        self.stdout.write(self.style.WARNING(f'Updated {count} objects.'))
        self.stdout.write(self.style.WARNING(f'Updated en-GB locale - {count}'))
