# Generated by Django 3.1.3 on 2022-03-03 08:56
from django.db import migrations, models, transaction
import django.db.models.deletion
import uuid


def migrate_handler(apps, schema_editor):
    KonovaCode = apps.get_model('codelist', 'KonovaCode')

    Responsibility = apps.get_model('intervention', 'Responsibility')
    Handler = apps.get_model('intervention', 'Handler')
    all_responsibs = Responsibility.objects.all()

    if all_responsibs.exists():
        handler_tmp_code = KonovaCode.objects.get(
            atom_id=710185,
        )

    with transaction.atomic():
        for resp in all_responsibs:
            handler_old = resp.handler_old
            handler = Handler.objects.create(
                type=handler_tmp_code,
                detail=handler_old
            )
            resp.handler = handler
            resp.save()


class Migration(migrations.Migration):

    dependencies = [
        ('codelist', '0001_initial'),
        ('intervention', '0003_intervention_teams'),
    ]

    operations = [
        migrations.CreateModel(
            name='Handler',
            fields=[
                ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
                ('detail', models.CharField(blank=True, max_length=500, null=True)),
                ('type', models.ForeignKey(blank=True, limit_choices_to={'code_lists__in': [1052], 'is_archived': False, 'is_selectable': True}, null=True, on_delete=django.db.models.deletion.SET_NULL, to='codelist.konovacode')),
            ],
            options={
                'abstract': False,
            },
        ),
        migrations.RenameField(
            model_name='responsibility',
            old_name='handler',
            new_name='handler_old',
        ),
        migrations.AddField(
            model_name='responsibility',
            name='handler',
            field=models.ForeignKey(blank=True, help_text="Refers to 'Eingriffsverursacher' or 'Maßnahmenträger'", null=True, on_delete=django.db.models.deletion.SET_NULL, to='intervention.handler'),
        ),
        migrations.RunPython(migrate_handler),
        migrations.RemoveField(
            model_name='responsibility',
            name='handler_old'
        ),
    ]
