# Generated by Django 3.0.4 on 2020-03-25 19:12
import uuid

from django.db import migrations, models


def make_many_contexts(apps, schema_editor):
    """
    Create a LTIContext with Forum.consumer and Forum.lti_context fields
    stored in the Forum object, and add it to the many-to-many relationship
    in Forum.lti_contexts
    """
    Forum = apps.get_model("forum", "Forum")
    LTIContext = apps.get_model("ashley", "LTIContext")

    for forum in Forum.objects.all():
        lti_context, _created = LTIContext.objects.get_or_create(
            lti_id=forum.lti_context, lti_consumer=forum.lti_consumer
        )
        forum.lti_contexts.add(lti_context)


def gen_uuid(apps, schema_editor):
    Forum = apps.get_model("forum", "Forum")
    for forum in Forum.objects.all():
        forum.lti_id = uuid.uuid4()
        forum.save(update_fields=["lti_id"])


class Migration(migrations.Migration):

    dependencies = [
        ("ashley", "0002_auto_20200325_1651"),
        ("forum", "0012_auto_20200311_1354"),
    ]

    operations = [
        migrations.AddField(
            model_name="forum",
            name="lti_contexts",
            field=models.ManyToManyField(to="ashley.LTIContext"),
        ),
        migrations.RunPython(make_many_contexts),
        migrations.RemoveField(model_name="forum", name="lti_consumer"),
        migrations.RemoveField(model_name="forum", name="lti_context"),
        migrations.AddField(
            model_name="forum",
            name="lti_id",
            field=models.UUIDField(default=uuid.uuid4, null=True),
        ),
        migrations.RunPython(gen_uuid, reverse_code=migrations.RunPython.noop),
        migrations.AlterField(
            model_name="forum",
            name="lti_id",
            field=models.UUIDField(default=uuid.uuid4, editable=False, unique=True),
        ),
    ]
