# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations
from django.conf import settings
import django_extensions.db.fields


def forwards_func(apps, schema_editor):
    MTPUser = apps.get_model("accounts", "MTPUser")
    db_alias = schema_editor.connection.alias

    old_through_model = MTPUser.temp_mgroups.through
    new_through_model = MTPUser.mgroups.through

    # We cannot use ``bulk_create`` because it does not call the ``save`` method and the
    # ``Syncable`` models need to call the ``save`` method for each update.
    for old_through_obj in old_through_model.objects.using(db_alias):
        new_through_model.objects.using(db_alias).create(
            user=old_through_obj.mtpuser, group=old_through_obj.group)

class Migration(migrations.Migration):

    dependencies = [
        ('sync', '0001_initial'),
        ('accounts', '0009_add_assessments_stuff'),
    ]

    operations = [
        migrations.CreateModel(
            name='GroupRole',
            fields=[
                ('id', django_extensions.db.fields.UUIDField(serialize=False, editable=False, blank=True, primary_key=True)),
                ('is_deleted', models.BooleanField(default=False)),
                ('update_locally', models.BooleanField(default=False)),
                ('role', models.CharField(choices=[('me', 'Member'), ('ma', 'Manager')], default='me', verbose_name='role', max_length=2)),
                ('first_update', models.ForeignKey(null=True, to='sync.Update', related_name='grouprole_by_first', blank=True)),
                ('group', models.ForeignKey(to='accounts.Group')),
                ('last_update', models.ForeignKey(null=True, to='sync.Update', related_name='grouprole_by_last', blank=True)),
            ],
            options={
                'abstract': False,
            },
        ),
        migrations.RenameField(
            model_name='mtpuser',
            old_name='mgroups',
            new_name='temp_mgroups'
        ),
        migrations.AddField(
            model_name='mtpuser',
            name='mgroups',
            field=models.ManyToManyField(through='accounts.GroupRole', to='accounts.Group', verbose_name='MTP Groups', related_name='members'),
        ),
        migrations.AddField(
            model_name='grouprole',
            name='user',
            field=models.ForeignKey(to=settings.AUTH_USER_MODEL),
        ),
        migrations.RunPython(
            forwards_func,
        ),
        migrations.RemoveField(
            model_name='mtpuser',
            name='temp_mgroups',
        ),
        migrations.AlterUniqueTogether(
            name='GroupRole',
            unique_together=set([('user', 'group')])
        ),
    ]
