# Generated by Django 3.2.18 on 2023-03-14 10:21

from django.db import migrations

from projectroles.app_settings import AppSettingAPI


def clean_up_app_settings(apps, schema_editor):
    app_settings = AppSettingAPI()
    AppSetting = apps.get_model('projectroles', 'AppSetting')
    # Find all app settings whith a project
    pr_settings = AppSetting.objects.exclude(project=None)
    for app_setting in pr_settings:
        try:
            app_name = (
                app_setting.app_plugin.name
                if app_setting.app_plugin
                else 'projectroles'
            )
            setting_def = app_settings.get_definition(
                app_name=app_name, name=app_setting.name
            )
        except ValueError:
            app_setting.delete()
            continue
        if app_setting.project.type not in setting_def.get(
            'project_types', ['PROJECT']
        ):
            # Delete app setting if it is not restricted to any project types
            app_setting.delete()


class Migration(migrations.Migration):

    dependencies = [
        ('projectroles', '0025_delete_projectusertag'),
    ]

    operations = [
        migrations.RunPython(
            clean_up_app_settings, reverse_code=migrations.RunPython.noop
        ),
    ]
