# Generated by Django 3.0.5 on 2020-04-17 08:35

from django.conf import settings
from django.db import migrations, models
from django.utils.module_loading import import_string


def get_plugin(plugins, plugin_name):
    for plugin in plugins:
        if plugin.PLUGIN_NAME == plugin_name:
            return plugin
    return None


def update_identifier_field(apps, schema):
    plugins = []
    for plugin_path in settings.PLUGINS:
        plugins.append(import_string(plugin_path))

    plugins_configuration = apps.get_model(
        "plugins", "PluginConfiguration"
    ).objects.all()

    for plugin_configuration in plugins_configuration:
        plugin = get_plugin(plugins, plugin_configuration.name)
        plugin_configuration.identifier = plugin.PLUGIN_ID
        plugin_configuration.save(update_fields=["identifier"])


class Migration(migrations.Migration):

    dependencies = [
        ("plugins", "0001_initial"),
    ]

    operations = [
        migrations.AddField(
            model_name="pluginconfiguration",
            name="identifier",
            field=models.CharField(default="default", max_length=128),
        ),
        migrations.AlterField(
            model_name="pluginconfiguration",
            name="name",
            field=models.CharField(max_length=128, blank=True, null=True),
        ),
        migrations.RunPython(update_identifier_field),
        migrations.AlterField(
            model_name="pluginconfiguration",
            name="identifier",
            field=models.CharField(max_length=128, unique=True),
            preserve_default=False,
        ),
    ]
