# Generated by Django 3.2.12 on 2022-04-21 10:03

from django.db import migrations

# pylint: disable=unused-argument
def move_old_meta_description_field_to_new_field(apps, schema_editor):
    AbstractBasePage = apps.get_model("ocyan_plugin_wagtail", "AbstractBasePage")
    ContentType = apps.get_model("contenttypes", "ContentType")
    
    # unfortunately we can't query it, because not all pages have the meta_description field.
    for page in AbstractBasePage.objects.all():
        try:
            ctype = ContentType.objects.get_for_id(page.content_type_id)
            specific_model = apps.get_model(ctype.app_label, ctype.model)
            page_specific = specific_model.objects.get(pk=page.pk)
        except LookupError:  # delete page types that nolonger exist
            page.delete()
            continue

        if not hasattr(page_specific, "meta_description"):
            continue

        # Save old meta description to the new field. if it is not empty.
        if page_specific.meta_description:
            page_specific.search_description = page_specific.meta_description
            page_specific.save()


class Migration(migrations.Migration):
    atomic = True

    dependencies = [
        ('ocyan_plugin_wagtail', '0022_ocyansettings_logo_alt'),
        ('contenttypes', '0001_initial'),
    ]

    operations = [
        migrations.RunPython(
            move_old_meta_description_field_to_new_field,
            migrations.RunPython.noop
        ),
    ]
