# -*- coding: utf-8 -*-
# Generated by Django 1.11.12 on 2018-04-27 04:28
from __future__ import unicode_literals

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


def associate_matchups_with_users(apps, schema_editor):
    Matchup = apps.get_model('matchups', 'Matchup')
    User = apps.get_model(settings.AUTH_USER_MODEL)

    for matchup in Matchup.objects.filter(email__isnull=False):
        matchup.user = User.objects.get(email=matchup.email)
        matchup.save()


class Migration(migrations.Migration):

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
        ('matchups', '0004_matchup_period_validator'),
    ]

    operations = [
        # Introduce the user field as nullable at first.
        migrations.AddField(
            model_name='matchup',
            name='user',
            field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='matchups', to=settings.AUTH_USER_MODEL),
        ),

        # Associate existing matchups with users by e-mail address.
        migrations.RunPython(associate_matchups_with_users),

        # Now add a non-null constraint.
        migrations.AlterField(
            model_name='matchup',
            name='user',
            field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='matchups', to=settings.AUTH_USER_MODEL),
        ),

        # Finally, remove the now-redundant e-mail field.
        migrations.RemoveField(
            model_name='matchup',
            name='email',
        ),
    ]
