# Generated by Django 1.9.11 on 2017-04-12 23:45

from django.db import migrations

ORIGINAL_UUID = "5ef6500e-0f8b-4eef-a6bd-075bcb655caa"


def build_full_name(apps, schema_editor):
    """
    For every Assay, build a name with the format [Line Name]-[Protocol Name]-[Name].
    """
    Assay = apps.get_model("main", "Assay")
    db_alias = schema_editor.connection.alias
    queryset = Assay.objects.using(db_alias).all()
    for assay in queryset.select_related("line", "protocol"):
        assay.name = "-".join([assay.line.name, assay.protocol.name, assay.name])
        assay.save()


def copy_original_name(apps, schema_editor):
    """
    For every Assay, copy the original name field value to a metadata field.
    """
    Assay = apps.get_model("main", "Assay")
    MetadataType = apps.get_model("main", "MetadataType")
    db_alias = schema_editor.connection.alias
    meta = MetadataType.objects.using(db_alias).get(uuid=ORIGINAL_UUID)
    for assay in Assay.objects.using(db_alias).all():
        assay.meta_store.update({str(meta.id): assay.name})
        assay.save()


def restore_original_name(apps, schema_editor):
    """
    For every Assay, copy the metadata field of original name back to name field.
    """
    Assay = apps.get_model("main", "Assay")
    MetadataType = apps.get_model("main", "MetadataType")
    db_alias = schema_editor.connection.alias
    meta = MetadataType.objects.using(db_alias).get(uuid=ORIGINAL_UUID)
    for assay in Assay.objects.using(db_alias).all():
        assay.name = assay.meta_store[str(meta.pk)]
        assay.save()
    pass


class Migration(migrations.Migration):

    dependencies = [("main", "0003_metabolite_pubchem")]

    operations = [
        # Copy original name to the created metadata type key; no need for a reverse operation
        migrations.RunPython(copy_original_name, migrations.RunPython.noop),
        # Set the name field to the full name; reverse restores the name from the metadata value
        migrations.RunPython(build_full_name, restore_original_name),
    ]
