# Generated by Django 2.1 on 2018-08-31 13:17

from django.db import migrations


def copy_motion_version_content_to_motion(apps, schema_editor):
    """
    Move all motion version content of the active version to the motion.
    """
    Motion = apps.get_model("motions", "Motion")

    for motion in Motion.objects.all():
        motion.title = motion.active_version.title
        motion.text = motion.active_version.text
        motion.reason = motion.active_version.reason
        motion.modified_final_version = motion.active_version.modified_final_version
        motion.amendment_paragraphs = motion.active_version.amendment_paragraphs
        motion.save(skip_autoupdate=True)


def migrate_active_change_recommendations(apps, schema_editor):
    """
    Delete all change recommendation of motion versions, that are not active. For active
    change recommendations the motion id will be set.
    """
    MotionChangeRecommendation = apps.get_model("motions", "MotionChangeRecommendation")
    to_delete = []
    for cr in MotionChangeRecommendation.objects.all():
        # chack if version id matches the active version of the motion
        if cr.motion_version.id == cr.motion_version.motion.active_version.id:
            cr.motion = cr.motion_version.motion
            cr.save(skip_autoupdate=True)
        else:
            to_delete.append(cr)

    # delete non active change recommendations
    for cr in to_delete:
        cr.delete(skip_autoupdate=True)


class Migration(migrations.Migration):

    dependencies = [("motions", "0011_motion_version_1")]

    operations = [
        # Copy old motion version data
        migrations.RunPython(copy_motion_version_content_to_motion),
        migrations.RunPython(migrate_active_change_recommendations),
    ]
