# -*- coding: utf-8 -*-
# Generated by Django 1.11.1 on 2019-07-23 16:25
from __future__ import unicode_literals
import json
from django.db import migrations, models

def populate_circle_user_references(apps, schema_editor):
    Circle = apps.get_model('groups', 'Circle')
    Membership = apps.get_model('users', 'Membership')

    for circle in Circle.objects.all():
        user_references = []
        memberships = Membership.objects.filter(group=circle.group,is_active=True)
        
        for membership in memberships:
            user_reference = {
                'id': membership.user.id,
                'newest_update': membership.user.person.newest_update
            }
            user_references.append(user_reference)
        
        circle.user_references = json.dumps(user_references, default=str)
        circle.user_count = len(user_references)
        circle.save()



class Migration(migrations.Migration):

    dependencies = [
        ('groups', '0010_add-name-to-group-circle'),
    ]

    operations = [
        migrations.AddField(
            model_name='circle',
            name='user_count',
            field=models.PositiveIntegerField(default=0),
        ),
        migrations.AddField(
            model_name='circle',
            name='user_references',
            field=models.TextField(default='[]'),
        ),
        migrations.RunPython(populate_circle_user_references),
    ]
