# Generated by Django 4.2 on 2023-11-29 13:20
import logging

from django.db import migrations
from django.conf import settings

logger = logging.getLogger(__name__)


def add_topics_to_m2m_table(apps, schema_editor):
    if hasattr(settings, "A4_PROJECT_TOPICS"):
        plans = apps.get_model("meinberlin_plans", "Plan")
        topic = apps.get_model("a4projects", "Topic")
        for plan in plans.objects.all():
            try:
                for topic_code in plan.topics.split(","):
                    if not topic_code:
                        continue
                    if len(topic_code) > 3:
                        logger.warning(
                            "warning: dropping unknown topic:"
                            + topic_code
                            + ". Max length is 3"
                        )
                        continue
                    plan_topic, _ = topic.objects.get_or_create(
                        code=topic_code,
                    )
                    plan.m2mtopics.add(plan_topic)
            except Exception as e:
                logger.warning(
                    "error migrating topics for plan " + plan.title + ": " + str(e)
                )
    else:
        pass


def reverse_func(apps, schema_editor):
    if hasattr(settings, "A4_PROJECT_TOPICS"):
        plans = apps.get_model("meinberlin_plans", "Plan")
        for plan in plans.objects.all():
            for topic in plan.m2mtopics.all():
                plan.m2mtopics.remove(topic)
    else:
        pass


class Migration(migrations.Migration):
    dependencies = [
        ("meinberlin_plans", "0058_plan_m2mtopics"),
    ]

    operations = [
        migrations.RunPython(add_topics_to_m2m_table, reverse_func),
    ]
