# Generated by Django 2.1.14 on 2019-11-29 07:21

import json

from django.db import migrations


def transfer_existing__model_paths(apps, schema_editor):
    """
    Iterating through objects.all() is pretty expensive usually
    as it makes multiple queries to the DB but in this case it cant
    be helped.
    """
    embeddings = apps.get_model("embedding", "Embedding")
    for embedding in embeddings.objects.all():
        if embedding.location:
            try:
                embedding_model_path = json.loads(embedding.location)["embedding"]
                phraser_model_path = json.loads(embedding.location)["phraser"]

                embedding.embedding_model.name = embedding_model_path
                embedding.phraser_model.name = phraser_model_path
                embedding.save()
            except:
                pass
        else:
            embedding.delete()

    embedding_clusters = apps.get_model("embedding", "EmbeddingCluster")
    for embedding_cluster in embedding_clusters.objects.all():
        if embedding_cluster.location:
            embedding_cluster_model_path = json.loads(embedding_cluster.location)["cluster"]
            embedding_cluster.cluster_model.name = embedding_cluster_model_path
            embedding_cluster.save()
        else:
            embedding_cluster.delete()


class Migration(migrations.Migration):
    dependencies = [
        ('embedding', '0003_add_model_path_fields'),
    ]

    operations = [
        migrations.RunPython(transfer_existing__model_paths)
    ]
