# Generated by Django 2.2.15 on 2020-09-03 23:28

from django.db import migrations


def migrate_number_children_questions_forward(apps, _schema_editor):
    def _convert_value(value):
        if int(value) > 0:
            return 'YES'
        return'NO'

    UserResponse = apps.get_model('core', 'UserResponse')
    under_19_responses = UserResponse.objects.filter(question_id='number_children_under_19')
    print(f"Converting {under_19_responses.count()} under 19 responses")
    for response in under_19_responses:
        response.value = _convert_value(response.value)
        response.question_id = 'has_children_under_19'
        response.save()

    over_19_responses = UserResponse.objects.filter(question_id='number_children_over_19')
    print(f"Converting {over_19_responses.count()} over 19 responses")
    for response in over_19_responses:
        UserResponse.objects.create(bceid_user=response.bceid_user, value=response.value, question_id='number_children_over_19_need_support')
        response.value = _convert_value(response.value)
        response.question_id = 'has_children_over_19'
        response.save()


def migrate_number_children_questions_backwards(apps, _schema_editor):
    UserResponse = apps.get_model('core', 'UserResponse')
    under_19_responses = UserResponse.objects.filter(question_id='has_children_under_19')
    print(f"Converting {under_19_responses.count()} under 19 responses")
    for response in under_19_responses:
        response.value = 1 if response.value == 'YES' else 0
        response.question_id = 'number_children_under_19'
        response.save()

    UserResponse.objects.filter(question_id='has_children_over_19').delete()
    UserResponse.objects.filter(question_id='number_children_over_19_need_support').update(question_id='number_children_over_19')


class Migration(migrations.Migration):
    dependencies = [
        ('core', '0019_auto_20191008_2141'),
    ]

    operations = [
        migrations.RunPython(migrate_number_children_questions_forward, migrate_number_children_questions_backwards)
    ]
