from django.core.management.base import BaseCommand
from tqdm import tqdm

from location.models import Address
from transfer.models import Locations


class Command(BaseCommand):
    help = """Fix address, clear number field and fill street_name_1 like in old db"""

    def handle(self, *args, **kwarg):
        addresses = Address.objects.filter(
            old_id__isnull=False
        ).values_list('old_id', flat=True)

        old_addresses = Locations.objects.filter(
            id__in=list(addresses)
        ).values_list('id', 'address')

        update_address = []
        for idx, address in tqdm(old_addresses):
            new_address = Address.objects.filter(old_id=idx).first()
            if new_address:
                new_address.number = 0
                new_address.street_name_2 = ''
                new_address.street_name_1 = address
                update_address.append(new_address)

        Address.objects.bulk_update(update_address, ['number', 'street_name_1', 'street_name_2'])
        self.stdout.write(self.style.WARNING(f'Updated addresses: {len(update_address)}'))
