# -*- coding: utf-8 -*-
# Generated by Django 1.11.14 on 2018-09-06 12:48
from __future__ import unicode_literals

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


def existing_subscriptions(apps, schema_editor):
    # Go through existing subscriptions and convert them from email to user
    Subscription = apps.get_model("core", "Subscription")
    User = apps.get_model("auth", "User")
    db_alias = schema_editor.connection.alias
    users = User.objects.using(db_alias).all()
    for subscription in Subscription.objects.using(db_alias).all():
        for user in users:
            # WARNING: User email is not unique.
            if subscription.email == user.email:
                subscription.email = None
                subscription.user = user
                subscription.save()


def reverse_existing_subscriptions(apps, schema_editor):
    # Go through existing subscriptions and convert them from email to user
    Subscription = apps.get_model("core", "Subscription")
    db_alias = schema_editor.connection.alias
    for subscription in Subscription.objects.using(db_alias).all():
        if subscription.user and subscription.user.email:
            subscription.email = subscription.user.email
            subscription.user = None
            subscription.save()


class Migration(migrations.Migration):

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
        ('core', '0087_test_known_issues'),
    ]

    operations = [
        migrations.AddField(
            model_name='subscription',
            name='user',
            field=models.ForeignKey(blank=True, default=None, null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL),
        ),
        migrations.AlterField(
            model_name='subscription',
            name='email',
            field=models.CharField(blank=True, max_length=1024, null=True, validators=[django.core.validators.EmailValidator()]),
        ),
        migrations.AlterUniqueTogether(
            name='subscription',
            unique_together=set([('project', 'user')]),
        ),
        migrations.RunPython(existing_subscriptions,
                             reverse_existing_subscriptions),
    ]
