# Generated by Django 4.0.2 on 2022-02-22 06:30

from django.db import migrations


def copy_relation(apps, schema_editor):
    RelationTypeNew = apps.get_model("label_types", "RelationType")
    RelationOld = apps.get_model("labels", "RelationOld")
    RelationNew = apps.get_model("labels", "RelationNew")
    Span = apps.get_model("labels", "Span")
    for relation_old in RelationOld.objects.all():
        from_id = Span.objects.get(id=relation_old.annotation_id_1)
        to_id = Span.objects.get(id=relation_old.annotation_id_2)
        relation_type = RelationTypeNew.objects.get(project=relation_old.type.project, text=relation_old.type.name)
        RelationNew(
            from_id=from_id, to_id=to_id, user=relation_old.user, type=relation_type, example=from_id.example
        ).save()


def delete_new_relation(apps, schema_editor):
    RelationNew = apps.get_model("labels", "RelationNew")
    RelationOld = apps.get_model("labels", "RelationOld")
    RelationTypeOld = apps.get_model("label_types", "RelationTypeOld")
    for relation in RelationNew.objects.all():
        relation_type, _ = RelationTypeOld.objects.get_or_create(
            project=relation.type.project, name=relation.type.text, color=relation.type.background_color
        )
        RelationOld(
            annotation_id_1=relation.from_id.id,
            annotation_id_2=relation.to_id.id,
            timestamp=relation.created_at,
            user=relation.user,
            project=relation.example.project,
            type=relation_type,
        ).save()
        relation.delete()


class Migration(migrations.Migration):

    dependencies = [
        ("labels", "0007_relationnew"),
    ]

    operations = [
        migrations.RunPython(code=copy_relation, reverse_code=delete_new_relation),
    ]
