# -*- coding: utf-8 -*-
# Generated by Django 1.11.29 on 2022-02-20 22:45
from __future__ import unicode_literals
from itertools import chain
from json import dumps, loads

from string import ascii_lowercase

from django.db import migrations, models
from django.utils.crypto import get_random_string
from django.utils.text import slugify
import django.db.models.deletion


def set_question_slug(apps, schema_editor):
    Question = apps.get_model("leprikon", "Question")
    SubjectRegistrationParticipant = apps.get_model("leprikon", "SubjectRegistrationParticipant")
    Participant = apps.get_model("leprikon", "SubjectRegistrationParticipant")

    new_keys = {}
    for question in Question.objects.all():
        question.slug = slugify(question.name)[:50]
        while Question.objects.filter(slug=question.slug).exists():
            slug_base = slugify(question.name)[:45]
            rand_string = get_random_string(4, ascii_lowercase)
            question.slug = f"{slug_base}-{rand_string}"
        question.save()
        new_keys[question.name] = question.slug

    for Model in (SubjectRegistrationParticipant, Participant):
        for obj in Model.objects.all():
            obj.answers = dumps({new_keys[key]: value for key, value in loads(obj.answers).items() if key in new_keys})
            obj.save()


class Migration(migrations.Migration):

    dependencies = [
        ("leprikon", "0068_participant_answers"),
    ]

    operations = [
        migrations.AddField(
            model_name="question",
            name="slug",
            field=models.SlugField(null=True, verbose_name="unique identifier"),
        ),
        migrations.RunPython(set_question_slug),
        migrations.AlterModelOptions(
            name="question",
            options={
                "ordering": ("name",),
                "verbose_name": "additional question",
                "verbose_name_plural": "additional questions",
            },
        ),
        migrations.AlterField(
            model_name="question",
            name="name",
            field=models.CharField(max_length=150, verbose_name="name"),
        ),
        migrations.AlterField(
            model_name="question",
            name="question",
            field=models.CharField(max_length=150, verbose_name="question"),
        ),
    ]
