# -*- coding: utf-8 -*-
# Generated by Django 1.10.6 on 2018-01-23 13:46
from __future__ import unicode_literals

import json

from django.db import migrations

def migrate_data(apps, schema_editor):
    FieldResult = apps.get_model("formly", "FieldResult")
    # alias for Field.MULTIPLE_TEXT
    MULTIPLE_TEXT_TYPE = 8
    multiple_text_results = FieldResult.objects.filter(question__field_type=MULTIPLE_TEXT_TYPE)
    print("\n")
    if multiple_text_results.exists() is False:
        print("formly-data-migration: No multiple text results data found.  Skipping data migration.")
        return

    print("formly-data-migration: Updating data on {} FieldResult instances".format(multiple_text_results.count()))
    for result in multiple_text_results:
        raw_answer = result.answer["answer"]
        if isinstance(raw_answer, unicode):
            try:
                answer = json.loads(raw_answer)
            except:
                answer = [raw_answer]
            result.answer["answer"] = answer
            result.save()
    print("formly-data-migration: Data update complete!")


class Migration(migrations.Migration):

    dependencies = [
        ("formly", "0011_field_mapping"),
    ]

    operations = [
        migrations.RunPython(migrate_data),
    ]

add data migration