# -*- coding: utf-8 -*-
# Generated by Django 1.11.21 on 2019-06-21 05:40
from __future__ import unicode_literals

import logging

from django.db import migrations

logger = logging.getLogger(__name__)


def attach_form_sub_answers_to_main_document(apps, schema_editor):
    """Answers to sub-questions of FormQuestions share document with parent."""
    Answer = apps.get_model("caluma_form", "Answer")
    to_delete = []

    count = Answer.objects.filter(question__type="form").count()

    for i, a in enumerate(Answer.objects.filter(question__type="form")):
        logger.info(f"    migrating... {i+1}/{count}")

        if a.value_document:
            for answer in a.value_document.answers.all():
                logger.debug(
                    f"moving answer {answer.pk} from {answer.document.pk} to root {a.document.family}"
                )
                answer.document_id = a.document.family
                answer.save()

            logger.debug(
                f"mark unused value document for deletion: {a.value_document.pk}"
            )
            to_delete.append(a.value_document)
        logger.debug(f"mark unused form answer for deletion: {a.pk}")
        to_delete.append(a)

    for obj in to_delete:
        logger.debug(f"deleting {obj} {obj.pk}")
        obj.delete()


def undo_attach_form_sub_answers_to_main_document(apps, schema_editor):
    """Provide a dummy for reverting migrations."""
    logger.warning(
        "Reverting '0018_remove_answer_value_document_data_migration'"
        "doesn't nest the answer structure."
    )


class Migration(migrations.Migration):

    dependencies = [("caluma_form", "0017_auto_20190619_1320")]

    operations = [
        migrations.RunPython(
            attach_form_sub_answers_to_main_document,
            undo_attach_form_sub_answers_to_main_document,
        )
    ]
