# Generated by Django 3.2.13 on 2022-08-26 13:40
import sys

from django.db import migrations
from edc_registration.models import RegisteredSubject
from edc_utils import get_utcnow
from tqdm import tqdm

from meta_rando.models import RandomizationList


def update_missing_sid_in_registeredsubject(apps, schema_editor):
    registered_subjects = RegisteredSubject.objects.filter(sid__isnull=True)
    sys.stdout.write(
        f"\n    (*) Found {registered_subjects.count()} records to update ... \n\n"
    )
    for rs_obj in tqdm(registered_subjects, total=registered_subjects.count()):
        rando_obj = RandomizationList.objects.get(subject_identifier=rs_obj.subject_identifier)
        rs_obj.sid = rando_obj.sid
        rs_obj.user_modified = "erikvw"
        rs_obj.modified = get_utcnow()
        rs_obj.comment = (
            f"{rs_obj.comment or ''}[manually updated SID from RandomizationList "
            "(meta_rando.migrations.0003)]."
        )
        rs_obj.save()
    sys.stdout.write(f"\n    Done\n")


class Migration(migrations.Migration):

    dependencies = [
        ("meta_rando", "0002_auto_20220704_1841"),
    ]

    operations = [migrations.RunPython(update_missing_sid_in_registeredsubject)]
