# Generated by Django 3.2.12 on 2022-02-04 13:32

from django.db import migrations


def fix_char_fields(model, fields):
    for field in fields:
        if getattr(model, field) is None:
            setattr(model, field, '')


def fix_json_fields(model, fields):
    for field in fields:
        if getattr(model, field) is None:
            setattr(model, field, [])


def run_data_migration(apps, schema_editor):
    Schema = apps.get_model('daiquiri_metadata', 'Schema')
    Table = apps.get_model('daiquiri_metadata', 'Table')
    Column = apps.get_model('daiquiri_metadata', 'Column')
    Function = apps.get_model('daiquiri_metadata', 'Function')

    for schema in Schema.objects.all():
        fix_char_fields(schema, ['title', 'description', 'long_description',
                                 'attribution', 'license', 'doi', 'utype'])
        fix_json_fields(schema, ['related_identifiers', 'creators', 'contributors'])
        schema.save()

    for table in Table.objects.all():
        fix_char_fields(table, ['title', 'description', 'long_description',
                                'attribution', 'license', 'doi', 'utype'])
        fix_json_fields(table, ['related_identifiers', 'creators', 'contributors'])
        table.save()

    for column in Column.objects.all():
        fix_char_fields(column, ['description', 'unit', 'ucd', 'utype', 'datatype'])
        column.save()

    for function in Function.objects.all():
        fix_char_fields(function, ['description'])
        function.save()


class Migration(migrations.Migration):

    dependencies = [
        ('daiquiri_metadata', '0031_change_order'),
    ]

    operations = [
        migrations.RunPython(run_data_migration)
    ]
