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

from django.conf import settings
from django.db import migrations
from django.db.models import Q

from weblate.auth.data import ACL_GROUPS, SELECTION_MANUAL, SELECTION_ALL


def handle_project(Group, Role, project):
    group = Group.objects.get_or_create(
        internal=True,
        name='{}@Billing'.format(project.name),
        project_selection=SELECTION_MANUAL,
        language_selection=SELECTION_ALL,
    )[0]
    group.projects.add(project)
    group.roles.set(
        Role.objects.filter(name=ACL_GROUPS['Billing']),
        clear=True
    )


def run_migration(apps, schema_editor):
    """Create new Billing group."""
    if 'weblate.billing' not in settings.INSTALLED_APPS:
        return
    Project = apps.get_model('trans', 'Project')
    Group = apps.get_model('weblate_auth', 'Group')
    Role = apps.get_model('weblate_auth', 'Role')
    Billing = apps.get_model('billing', 'Billing')

    # Private and protected projects
    for project in Project.objects.filter(access_control__in=(1, 100)):
        handle_project(Group, Role, project)
    for billing in Billing.objects.all():
        for project in billing.projects.all():
            handle_project(Group, Role, project)


class Migration(migrations.Migration):

    dependencies = [
        ('weblate_auth', '0009_auto_20180509_1552'),
    ]

    operations = [
        migrations.RunPython(run_migration, reverse_code=run_migration)
    ]
