# Generated by Django 2.2.8 on 2020-04-08 11:22

import functools
import logging

import phonenumbers
from django.db import migrations, models

import eventstore.validators

logger = logging.getLogger(__name__)


def normalise_msisdn(apps, schema_editor):
    Covid19Triage = apps.get_model("eventstore", "Covid19Triage")
    for triage in Covid19Triage.objects.all().iterator():
        try:
            number = phonenumbers.parse(triage.msisdn, "ZA")
            triage.msisdn = phonenumbers.format_number(
                number, phonenumbers.PhoneNumberFormat.E164
            )
            triage.save(update_fields=("msisdn",))
        except:
            # Try to normalise msisdn, log warning if unable to, because it will have
            # to be manually corrected
            logger.warning(
                f"Unable to normalise msisdn {triage.msisdn} for Covid19Triage "
                f"{triage.id}"
            )


class Migration(migrations.Migration):

    dependencies = [("eventstore", "0026_add_whatsapp_fields_covid19triage")]

    operations = [
        migrations.AlterField(
            model_name="covid19triage",
            name="msisdn",
            field=models.CharField(
                max_length=255,
                validators=[
                    functools.partial(
                        eventstore.validators._phone_number, *(), **{"country": "ZA"}
                    )
                ],
            ),
        ),
        migrations.RunPython(normalise_msisdn),
    ]
