# Generated by Django 4.2.11 on 2024-06-11 21:54
from django.db import migrations
from edc_model.utils import InvalidFormat, duration_hm_to_timedelta
from tqdm import tqdm


def update_durations(apps, schema_editor):
    for model, fldname in [
        ("intecomm_subject.dminitialreview", "glucose_fasting_duration_delta"),
        ("intecomm_subject.dmreview", "glucose_fasting_duration_delta"),
        ("intecomm_subject.glucose", "glucose_fasting_duration_delta"),
    ]:
        print(model)
        model_cls = apps.get_model(model)
        qs = model_cls.objects.all()
        total = qs.count()
        for obj in tqdm(qs, total=total):
            if duration_text := obj.glucose_fasting_duration_str:
                try:
                    obj.glucose_fasting_duration_delta = duration_hm_to_timedelta(
                        duration_text
                    )
                except (TypeError, InvalidFormat):
                    print(obj)
                else:
                    obj.save_base(update_fields=[fldname])
    for model, fldname in [
        ("intecomm_subject.careseekinga", "travel_tdelta"),
        ("intecomm_subject.careseekingb", "travel_tdelta"),
    ]:
        print(model)
        model_cls = apps.get_model(model)
        qs = model_cls.objects.all()
        total = qs.count()
        for obj in tqdm(qs, total=total):
            if duration_text := obj.travel_duration:
                try:
                    obj.travel_tdelta = duration_hm_to_timedelta(duration_text)
                except (TypeError, InvalidFormat):
                    print(obj)
                else:
                    obj.save_base(update_fields=[fldname])


class Migration(migrations.Migration):

    dependencies = [
        ("intecomm_subject", "0185_rename_currentconditions_diagnoses_and_more"),
    ]

    operations = [migrations.RunPython(update_durations)]
