# -*- coding: utf-8 -*-
# Generated by Django 1.10.8 on 2018-02-09 07:18
from __future__ import unicode_literals

import django.db.models.deletion
from django.conf import settings
from django.contrib.auth.models import AnonymousUser
from django.db import migrations, models

import openslides.utils.models


def move_submitters_to_own_model(apps, schema_editor):
    Motion = apps.get_model('motions', 'Motion')
    Submitter = apps.get_model('motions', 'Submitter')

    for motion in Motion.objects.all():
        weight = 0
        for user in motion.submittersOld.all():
            # We cannot use the add method here, so do it manually...
            if Submitter.objects.filter(user=user, motion=motion).exists():
                continue  # The user is already a submitter. Skip this duplicate.
            if isinstance(user, AnonymousUser):
                continue  # Skip the anonymous

            submitter = Submitter(user=user, motion=motion, weight=weight)
            submitter.save(force_insert=True)
            weight += 1


class Migration(migrations.Migration):

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
        ('motions', '0005_auto_20180202_1318'),
    ]

    operations = [
        migrations.RenameField(
            model_name='motion',
            old_name='submitters',
            new_name='submittersOld',
        ),
        migrations.CreateModel(
            name='Submitter',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('weight', models.IntegerField(null=True)),
            ],
            options={
                'default_permissions': (),
            },
            bases=(openslides.utils.models.RESTModelMixin, models.Model),
        ),
        migrations.AddField(
            model_name='submitter',
            name='motion',
            field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='submitters', to='motions.Motion'),
        ),
        migrations.AddField(
            model_name='submitter',
            name='user',
            field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL),
        ),
        migrations.RunPython(
            move_submitters_to_own_model
        ),
        migrations.RemoveField(
            model_name='motion',
            name='submittersOld',
        ),
    ]
