# Generated by Django 3.0.9 on 2020-08-26 16:24

from django.db import migrations
from django.db.models.signals import pre_save
from edc_utils import DisableSignals


def update_from_reason_for_visit(apps, schema_editor):
    subject_visit_model_cls = apps.get_model("inte_subject.subjectvisit")
    reason_for_visit_model_cls = apps.get_model("inte_subject.reasonforvisit")
    medications_model_cls = apps.get_model("inte_subject.medications")

    for reason_for_visit in reason_for_visit_model_cls.objects.all():
        subject_visit = subject_visit_model_cls.objects.get(
            id=reason_for_visit.subject_visit_id
        )
        for obj in reason_for_visit.clinic_services.all():
            subject_visit.clinic_services.add(obj)
        for obj in reason_for_visit.health_services.all():
            subject_visit.health_services.add(obj)
        medications = medications_model_cls()
        medications.created = reason_for_visit.created
        medications.modified = reason_for_visit.modified
        medications.user_created = reason_for_visit.user_created
        medications.user_modified = reason_for_visit.user_modified
        medications.hostname_created = reason_for_visit.hostname_created
        medications.hostname_modified = reason_for_visit.hostname_modified
        medications.device_created = reason_for_visit.device_created
        medications.device_modified = reason_for_visit.device_modified
        medications.consent_model = reason_for_visit.consent_model
        medications.consent_version = reason_for_visit.consent_version
        medications.site_id = reason_for_visit.site_id
        medications.subject_visit_id = reason_for_visit.subject_visit_id
        medications.report_datetime = reason_for_visit.report_datetime
        medications.refill_hiv = reason_for_visit.refill_hiv
        medications.refill_diabetes = reason_for_visit.refill_diabetes
        medications.refill_hypertension = reason_for_visit.refill_hypertension
        medications.crf_status = reason_for_visit.crf_status
        medications.crf_status_comments = reason_for_visit.crf_status_comments
        with DisableSignals(disabled_signals=[pre_save]):
            medications.save()
            subject_visit.save()


class Migration(migrations.Migration):

    dependencies = [
        ("inte_subject", "0041_auto_20200826_1913"),
    ]

    operations = [migrations.RunPython(update_from_reason_for_visit)]
