# -*- coding: utf-8 -*-
# Generated by Django 1.11.13 on 2018-05-08 09:23
from __future__ import unicode_literals

from django.db import migrations

from weblate.auth.data import ACL_GROUPS
from weblate.auth.utils import migrate_groups


def run_migration(apps, schema_editor):
    Role = apps.get_model('weblate_auth', 'Role')
    Group = apps.get_model('weblate_auth', 'Group')
    GroupACL = apps.get_model('permissions', 'GroupACL')
    Language = apps.get_model('lang', 'Language')

    # Bring group definitions up to date
    # Either creates them (on fresh install) or sets
    # default roles for migrated ones
    migrate_groups(Group, Role, update=True)

    # Remove possible old template groups which are no longer
    # used
    Group.objects.filter(name__startswith='@').delete()

    # Adjust roles for migrated groups
    for group in Group.objects.filter(name__contains='@'):
        name = group.name.split('@', 1)[1]
        if name not in ACL_GROUPS:
            continue
        group.roles.set(
            Role.objects.filter(name=ACL_GROUPS[name]),
        )
        for groupacl in GroupACL.objects.filter(groups=group.id):
            if groupacl.project:
                group.projects.add(groupacl.project)
        group.internal = True
        group.save(update_fields=['internal'])

    # Apply all languages selector
    for group in Group.objects.all():
        group.languages.set(Language.objects.all())


class Migration(migrations.Migration):

    dependencies = [
        ('weblate_auth', '0004_auto_20180508_1032'),
        ('permissions', '0009_auto_20180416_1610'),
        ('lang', '0011_auto_20180215_1158'),
    ]

    operations = [
        migrations.RunPython(run_migration),
    ]
