# Generated by Django 3.2.15 on 2022-09-22 18:28

from django.db import migrations
from django.forms.models import model_to_dict


def migrate_session_material(apps, schema_editor):
    """Migrate the session material to session material relation"""
    SessionMaterial = apps.get_model("programme", "SessionMaterial")
    SessionMaterialRelation = apps.get_model(
        "programme", "SessionMaterialRelation"
    )
    Material = apps.get_model("uploaded_material", "Material")
    for material in list(SessionMaterial.objects.all()):
        real_material = Material.objects.get(pk=material.pk)
        if not SessionMaterialRelation.objects.filter(
            material__pk=real_material.pk
        ):
            SessionMaterialRelation.objects.create(
                material=real_material,
                session=material.session,
                registered_only=material.registered_only,
                pinned=material.pinned,
            )
            material.delete(keep_parents=True)


def undo_migrate_session_material(apps, schema_editor):
    """Migrate the session material relation to session material"""
    SessionMaterial = apps.get_model("programme", "SessionMaterial")
    SessionMaterialRelation = apps.get_model(
        "programme", "SessionMaterialRelation"
    )
    for materialrelation in list(SessionMaterialRelation.objects.all()):
        material = materialrelation.material
        kws = model_to_dict(materialrelation)
        kws.pop("material")
        kws.update(model_to_dict(material))
        kws["user"] = material.user
        kws["category"] = material.category
        kws["license"] = material.license
        kws["date_created"] = material.date_created
        SessionMaterial.objects.create(material_ptr=material, **kws)


class Migration(migrations.Migration):

    dependencies = [
        ("programme", "0022_auto_20220922_2028"),
    ]

    operations = [
        migrations.RunPython(
            migrate_session_material, undo_migrate_session_material
        ),
        migrations.RemoveField(
            model_name="sessionmaterial",
            name="material_ptr",
        ),
        migrations.RemoveField(
            model_name="sessionmaterial",
            name="session",
        ),
        migrations.DeleteModel(
            name="SessionMaterial",
        ),
    ]
