from django.core.management.base import BaseCommand
from django.db.models import Q

from establishment.models import Establishment
from transfer.models import Reviews


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

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

        queryset = Reviews.objects.exclude(
            Q(establishment_id__isnull=True) |
            Q(mark__isnull=True)
        ).filter(aasm_state='published').values_list('establishment_id', 'mark', 'updated_at')

        for es_id, new_mark, new_date in queryset:
            try:
                mark, date = valid_data[es_id]
            except KeyError:
                valid_data[es_id] = (new_mark, new_date)
            else:
                if new_date > date:
                    valid_data[es_id] = (new_mark, new_date)

        for key, value in valid_data.items():
            try:
                establishment = Establishment.objects.get(old_id=key)
            except Establishment.DoesNotExist:
                continue
            except Establishment.MultipleObjectsReturned:
                establishment = Establishment.objects.filter(old_id=key).first()
            else:
                establishment.public_mark = int(value[0])
                establishment.save()
                count += 1

        self.stdout.write(self.style.WARNING(f'Updated {count} objects.'))
