# -*- coding: utf-8 -*-
# Generated by Django 1.9.13 on 2017-09-25 05:00
from __future__ import unicode_literals

from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion


def add_editors(apps, schema_editor):
    Theory = apps.get_model("character", "Theory")
    TheoryPermissions = apps.get_model("character", "TheoryPermissions")
    for theory in Theory.objects.all():
        editors = list(theory.can_edit.all())
        objects = []
        for player in theory.known_by.all():
            if player in editors or theory.creator == player:
                can_edit = True
            else:
                can_edit = False
            objects.append(TheoryPermissions(player=player, theory=theory, can_edit=can_edit))
        TheoryPermissions.objects.bulk_create(objects)


class Migration(migrations.Migration):

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
        ('character', '0015_auto_20170605_2252'),
    ]

    operations = [
        migrations.CreateModel(
            name='TheoryPermissions',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('can_edit', models.BooleanField(default=False)),
                ('player', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='theory_permissions', to=settings.AUTH_USER_MODEL)),
                ('theory', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='theory_permissions', to='character.Theory')),
            ],
            options={
                'abstract': False,
            },
        ),
        migrations.AddField(
            model_name='theory',
            name='known_by2',
            field=models.ManyToManyField(blank=True, null=True, related_name='known_theories2', through='character.TheoryPermissions', to=settings.AUTH_USER_MODEL),
        ),
        migrations.RunPython(add_editors)
    ]
