# -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-04-19 14:53
from __future__ import unicode_literals

import json
import temba.utils.models

from django.contrib.postgres.operations import HStoreExtension
from django.db import migrations


def populate_message_new(apps, schema_editor):
    CampaignEvent = apps.get_model('campaigns', 'CampaignEvent')
    events = list(CampaignEvent.objects.filter(event_type='M').select_related('flow'))

    for event in events:
        try:
            event.message_new = json.loads(event.message)
        except Exception:
            event.message_new = {event.flow.base_language: event.message}

        event.save(update_fields=('message_new',))

    if events:
        print("Converted %d campaign events" % len(events))


class Migration(migrations.Migration):

    dependencies = [
        ('campaigns', '0014_auto_20170228_0837'),
    ]

    operations = [
        HStoreExtension(),
        migrations.AddField(
            model_name='campaignevent',
            name='message_new',
            field=temba.utils.models.TranslatableField(max_length=640, null=True),
        ),
        migrations.RunPython(populate_message_new)
    ]

# -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-04-19 14:53
from __future__ import unicode_literals

import json
import temba.utils.models

from django.contrib.postgres.operations import HStoreExtension
from django.db import migrations


def populate_message_new(apps, schema_editor):
    CampaignEvent = apps.get_model('campaigns', 'CampaignEvent')
    events = list(CampaignEvent.objects.filter(event_type='M').select_related('flow'))

    for event in events:
        try:
            event.message_new = json.loads(event.message)
        except Exception:
            base_lang = event.flow.base_language or 'base'
            event.message_new = {base_lang: event.message}

        event.save(update_fields=('message_new',))

    if events:
        print("Converted %d campaign events" % len(events))


class Migration(migrations.Migration):

    dependencies = [
        ('campaigns', '0014_auto_20170228_0837'),
    ]

    operations = [
        HStoreExtension(),
        migrations.AddField(
            model_name='campaignevent',
            name='message_new',
            field=temba.utils.models.TranslatableField(max_length=640, null=True),
        ),
        migrations.RunPython(populate_message_new)
    ]

Fix migration to work with flows with no base_language
Fix migration to work with flows with no base_language
