# Generated by Django 2.0.13 on 2019-08-18 19:30

from django.db import migrations


TYPE_RECIPE_EDITED = 'recipe_edited'
TYPE_RECIPE_RATED = 'recipe_rated'


def forwards(apps, schema_editor):
    'Split EDITED NewsItems where rating changed into a RATED NewsItem'
    NewsItem = apps.get_model("core", "NewsItem")

    for ni in NewsItem.objects.filter(type=TYPE_RECIPE_EDITED):
        if 'rating' in ni.payload['fields_changed']:
            ni.payload['fields_changed'].remove('rating')

            # If only rating changed, then change the type to RATED
            if not ni.payload['fields_changed']:
                print(f'Changing NewsItem {ni.id} from EDITED to RATED')
                ni.type = TYPE_RECIPE_RATED
                del ni.payload['fields_changed']
                ni.save()
            # Otherwise split the "rating" action into a separate NewsItem
            else:
                ni.save()

                new_payload = ni.payload.copy()
                del new_payload['fields_changed']
                new_payload['original_newsitem'] = ni.id
                ni2 = NewsItem.objects.create(
                    paprika_account=ni.paprika_account,
                    type=TYPE_RECIPE_RATED,
                    payload=new_payload,
                )
                ni2.created_date = ni.created_date
                ni2.save()
                print(f'Spliting NewsItem {ni.id} ({ni.payload["fields_changed"]}) into new NewsItem {ni2.id}')


def backwards(apps, schema_editor):
    'Recombine RATED NewsItems with their original EDITED NewsItems'
    NewsItem = apps.get_model("core", "NewsItem")

    for ni in NewsItem.objects.filter(type=TYPE_RECIPE_RATED):
        orig_ni_id = ni.payload.get('original_newsitem')
        if orig_ni_id:
            orig_ni = NewsItem.objects.get(id=orig_ni_id)
            orig_ni.payload['fields_changed'].append('rating')
            orig_ni.save()
            print(f'Merging NewsItem {ni.id} into NewsItem {orig_ni.id} ({orig_ni.payload["fields_changed"]})')
            ni.delete()
        else:
            print(f'Changing NewsItem {ni.id} from RATED to EDITED')
            ni.type = TYPE_RECIPE_EDITED
            ni.payload['fields_changed'] = ['rating']
            ni.save()


class Migration(migrations.Migration):

    dependencies = [
        ('core', '0021_auto_20190818_1929'),
    ]

    operations = [
        migrations.RunPython(forwards, backwards),
    ]
