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

from location.models import Country


class Command(BaseCommand):
    help = """Added calling code to existed countries."""

    def handle(self, *args, **kwarg):
        country_qs = Country.objects.filter(
            code__in=[
                country_code.lower() for country_code in settings.COUNTRY_CALLING_CODES.keys()
            ])

        to_update = []
        for country in tqdm(country_qs, desc='Iterate over countries'):
            if str(country.calling_code) != str(settings.COUNTRY_CALLING_CODES[country.code.lower()]):
                country.calling_code = settings.COUNTRY_CALLING_CODES[country.code.lower()]
                to_update.append(country)

        Country.objects.bulk_update(to_update, ['calling_code', ])
        self.stdout.write(self.style.WARNING(f'Updated {len(to_update)} countries'))
