# Generated by Django 3.0.9 on 2020-09-10 18:11
from copy import copy

from django.db import migrations
from django.db.models.signals import pre_save
from edc_constants.constants import NEG, NEVER, NO, NOT_APPLICABLE, POS, YES
from edc_utils import DisableSignals


class DataMigrationError(Exception):
    pass


def convert_clinical_review_hiv_dx(apps, schema_editor):
    clinical_review_baseline_model_cls = apps.get_model("inte_subject.clinicalreviewbaseline")
    for obj in clinical_review_baseline_model_cls.objects.all():
        hiv_status = copy(obj.hiv_test)
        if hiv_status == NEVER:
            obj.hiv_test = NO
            obj.hiv_dx = NOT_APPLICABLE
            with DisableSignals(disabled_signals=[pre_save]):
                obj.save()
        elif hiv_status == POS:
            obj.hiv_test = YES
            obj.hiv_dx = YES
            with DisableSignals(disabled_signals=[pre_save]):
                obj.save()
        elif hiv_status == NEG:
            obj.hiv_test = YES
            obj.hiv_dx = NO
            with DisableSignals(disabled_signals=[pre_save]):
                obj.save()
        else:
            raise DataMigrationError(f"Invalid response. Got hiv_test==`{hiv_status}`")


class Migration(migrations.Migration):

    dependencies = [
        ("inte_subject", "0050_auto_20200910_2110"),
    ]

    operations = [migrations.RunPython(convert_clinical_review_hiv_dx)]
