# Generated by Django 1.11.20 on 2019-06-12 21:27

from collections import Counter

from django.db import migrations, models


def set_fcaccount_order(apps, schema_editor):
    FcAccount = apps.get_model('authentic2_auth_fc', 'FcAccount')
    c = Counter()
    FcAccount.objects.update(order=0)
    user_ids = (
        FcAccount.objects.values('user_id')
        .annotate(total=models.Count('id'))
        .filter(total__gt=1)
        .values_list('user_id', flat=True)
    )
    subs = (
        FcAccount.objects.values_list('sub')
        .annotate(total=models.Count('id'))
        .filter(total__gt=1)
        .values_list('sub', flat=True)
    )

    for account in FcAccount.objects.filter(models.Q(user_id__in=user_ids) | models.Q(sub__in=subs)):
        order = max(c[account.user_id], c[account.sub])
        if account.order != order:
            account.order = order
            account.save()
        order += 1
        c[account.user_id] = order
        c[account.sub] = order
    assert FcAccount.objects.filter(order__isnull=True).count() == 0


def noop(apps, schema_editor):
    pass


class Migration(migrations.Migration):
    # Disembiguate sub and user_id columns using an integer order column, then
    # force sub/order and user_id/order pairs unique to be unique in order
    # to move to a model where user and sub are unique without breaking on existing data

    dependencies = [
        ('authentic2_auth_fc', '0002_auto_20200416_1439'),
    ]

    operations = [
        migrations.AddField(
            model_name='fcaccount',
            name='order',
            field=models.PositiveIntegerField(null=True, verbose_name='order'),
        ),
        migrations.RunPython(set_fcaccount_order, noop),
    ]
