# Generated by Django 2.0.4 on 2018-07-06 18:02

from django.db import migrations


def migrate_to_entry_versions(apps, schema_editor):
    if schema_editor.connection.alias != 'default':
        return
    Entry = apps.get_model("palanaeum", "Entry")
    EntryVersion = apps.get_model("palanaeum", "EntryVersion")
    ImageSource = apps.get_model("palanaeum", "ImageSource")
    URLSource = apps.get_model("palanaeum", "URLSource")
    Snippet = apps.get_model("palanaeum", "Snippet")

    # Move tags to EntryVersion
    for entry_version in EntryVersion.objects.prefetch_related('entry__tags'):
        for tag in entry_version.entry.tags.all():
            entry_version.tags.add(tag)

    # Move date and paraphrased flag to Version
    for entry in Entry.objects.all():
        EntryVersion.objects.filter(entry=entry).update(entry_date=entry.date, paraphrased=entry.paraphrased)

    # Move URLSource
    for url_src in URLSource.objects.all():
        for entry in url_src.entries.all():
            for entry_version in entry.versions.all():
                url_src.entry_versions.add(entry_version)


def migrate_to_entries(apps, schema_editor):
    if schema_editor.connection.alias != 'default':
        return
    Entry = apps.get_model("palanaeum", "Entry")
    ImageSource = apps.get_model("palanaeum", "ImageSource")
    URLSource = apps.get_model("palanaeum", "URLSource")
    Snippet = apps.get_model("palanaeum", "Snippet")

    # Move from EntryVersions
    for entry in Entry.objects.all():
        last_version = entry.versions.last()
        if not last_version:
            continue
        for tag in last_version.tags.all():
            entry.tags.add(tag)

    # Move date and paraphrased to Entry
    for entry in Entry.objects.all():
        last_version = entry.versions.last()
        if not last_version:
            continue
        entry.date = last_version.entry_date
        entry.paraphrased = last_version.paraphrased
        entry.save()

    # Move entry assignment in URLSource
    for url_src in URLSource.objects.all():
        if url_src.entry_versions.exists():
            entries = {v.entry for v in url_src.entry_versions.all()}
            for entry in entries:
                url_src.entries.add(entry)


class Migration(migrations.Migration):

    dependencies = [
        ('palanaeum', '0003_auto_20180706_1802'),
    ]

    operations = [
        migrations.RunPython(migrate_to_entry_versions, reverse_code=migrate_to_entries)
    ]
