# Generated by Django 3.2.16 on 2022-11-08 19:12

from django.db import migrations, models

import yaml


def parse_date(apps, schema_editor):
    """Parse dates from snippet."""
    ModulemdObsolete = apps.get_model("rpm", "ModulemdObsolete")

    obsoletes_to_update = []

    for obsolete in ModulemdObsolete.objects.all():
        parsed_snippet = yaml.safe_load(obsolete.snippet)
        obsolete.modified = parsed_snippet['data']['modified']
        if parsed_snippet['data'].get('eol_date'):
            obsolete.eol_date = parsed_snippet['data'].get('eol_date')
        obsoletes_to_update.append(obsolete)

    ModulemdObsolete.objects.bulk_update(obsoletes_to_update, ["modified", "eol_date"])


def clean_date_fields(apps, schema_editor):
    """Emtpy date fields."""
    ModulemdObsolete = apps.get_model("rpm", "ModulemdObsolete")
    obsoletes_to_update = []

    for obsolete in ModulemdObsolete.objects.all():
        obsolete.modified = None
        obsolete.eol_date = None

    ModulemdObsolete.objects.bulk_update(obsoletes_to_update, ["modified", "eol_date"])


class Migration(migrations.Migration):

    dependencies = [
        ('rpm', '0046_rbac_perms'),
    ]

    operations = [
        migrations.AlterField(
            model_name='modulemdobsolete',
            name='modified',
            field=models.DateTimeField(null=True),
        ),
        migrations.AlterField(
            model_name='modulemdobsolete',
            name='eol_date',
            field=models.DateTimeField(null=True),
        ),
        migrations.RunPython(clean_date_fields),
        migrations.AlterField(
            model_name='modulemdobsolete',
            name='eol_date',
            field=models.TextField(null=True),
        ),
        migrations.AlterField(
            model_name='modulemdobsolete',
            name='modified',
            field=models.TextField(),
        ),
        migrations.RunPython(parse_date),
    ]
