# Generated by Django 2.2.3 on 2019-08-09 16:29

from django.db import migrations
from datetime import date

EDITED_POSTS = [
    {
        "slug": "django-10-released",
        "pub_date": date(2008, 9, 3),
    },
    {
        "slug": "simple-robots-for-sale",
        "pub_date": date(2011, 2, 21),
    },
    {
        "slug": "django-training",
        "pub_date": date(2013, 1, 18),
    },
    {
        "slug": "django-18-released",
        "pub_date": date(2015, 4, 1),
    },
    {
        "slug": "more-django-info",
        "pub_date": date(2015, 4, 8),
    },
    {
        "slug": "new-django-version",
        "pub_date": date(2020, 5, 15),
    },
]

UNEDITED_POSTS = []

def edit_post_date(apps, schema_editor):
    
    Post = apps.get_model('blog', 'Post')
    assert (len(EDITED_POSTS) == len(Post.objects.all())), "EDITED_POSTS != Post objects"
    for post_data in EDITED_POSTS:
        editee_post = Post.objects.get(slug__iexact = post_data["slug"])
        UNEDITED_POSTS.append({
            "slug": post_data["slug"],
            "pub_date": post_data["pub_date"]
        })
        editee_post.pub_date = post_data["pub_date"]
        editee_post.save()

def revert_edit_post_date(apps, schema_editor):
    Post = apps.get_model("blog", "Post")
    assert (UNEDITED_POSTS != 0), "You cannot run this function yet."
    for post_data in UNEDITED_POSTS:
        editee_post = Post.objects.get(slug__iexact = post_data["slug"])
        editee_post.pub_date = post_data["pub_date"]
        editee_post.save()

class Migration(migrations.Migration):

    dependencies = [
        ('blog', '0003_post_fields_startups_and_tags_optional'),
    ]

    operations = [
        migrations.RunPython(
            edit_post_date,
            revert_edit_post_date
        )
    ]