# -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2016-06-08 12:18
from __future__ import unicode_literals

from django.core.management.sql import emit_post_migrate_signal
from django.db import migrations

import base.models as mdl
from base.auth.roles import tutor as tutor_mdl


def add_users_to_group(apps, schema_editor):
    db_alias = schema_editor.connection.alias
    emit_post_migrate_signal(1, False, db_alias)
    Group = apps.get_model("auth", "Group")
    User = apps.get_model("auth", "User")
    tutors_group = Group.objects.get(name='tutors')
    students_group = Group.objects.get(name='students')
    for user in list(User.objects.all()):
        person = mdl.person.find_by_user(user)
        if person:
            # Check Tutor
            if tutor_mdl.find_by_person(person) and tutors_group:
                user.groups.add(tutors_group)
            # Check Student
            if mdl.student.find_by_person(person) and students_group:
                user.groups.add(students_group)


class Migration(migrations.Migration):

    dependencies = [
        ('base', '0057_creation_and_initialisation_of_groups'),
        ('contenttypes', '__latest__'),
    ]

    operations = [
        migrations.RunPython(add_users_to_group, elidable=True, reverse_code=migrations.RunPython.noop),
    ]
