# Generated by Django 4.1.7 on 2023-05-10 00:52
import sys

from django.db import migrations
from django.db.migrations import RunPython
from django.db.models import Q
from tqdm import tqdm

from intecomm_screening.identifiers import FilingIdentifier, PatientLogIdentifier


def update_identifiers(apps, schema_editor):
    sys.stdout.write(
        "\nUpdating filing_identifier and patient_log_identifier if still UUIDs ...\n"
    )
    qs = apps.get_model("intecomm_screening.patientlog").objects.exclude(
        Q(filing_identifier__startswith="F") | Q(patient_log_identifier__startswith="P")
    )
    sys.stdout.write(f"Found {qs.count()} records to update.\n")
    for obj in tqdm(qs, total=qs.count()):
        obj.filing_identifier = FilingIdentifier(site_id=obj.site_id).identifier
        obj.patient_log_identifier = PatientLogIdentifier(site_id=obj.site_id).identifier
        obj.save_base(update_fields=["filing_identifier", "patient_log_identifier"])
    sys.stdout.write("\nDone.\n")


class Migration(migrations.Migration):
    dependencies = [
        ("intecomm_screening", "0029_alter_historicalpatientlog_filing_identifier_and_more"),
    ]

    operations = [RunPython(update_identifiers)]
