# -*- coding: utf-8 -*-
# Generated by Django 1.11.20 on 2019-09-17 15:37
from __future__ import unicode_literals

from django.core.exceptions import ObjectDoesNotExist
from django.db import migrations
from guardian.models import GroupObjectPermission, Permission
from guardian.shortcuts import assign_perm, get_groups_with_perms
from guardian.ctypes import get_content_type

from turkle.models import Batch, Project


def copy_project_settings_to_batch(apps, schema_editor):
    """Copy relevant settings from Projects to their associated Batches

    - 'can_work_on' permission from Projects to associated Batches
    - 'custom_permissions' value from Projects to associated Batches
    - 'login_required' value from Projects to associated Batches
    """
    # HACK: Circumventing a bizzare migration issue with Django-Guardian,
    # which is hopefully fixed in newer versions of Django and Django-Guardian.
    # (Current Django version is 1.11.x, Django-Guardian version is 1.4.9)
    #
    # Migration step 0002 should create the Django-Guardian Permission
    # for 'can_work_on_batch'.  Migration step 0005 (this step) tries
    # to access this Permission.  If migration steps 0002 and 0005
    # are run as part of the same 'manage.py migrate' command, then an
    # exception is thrown because step 0005 cannot retrieve the
    # 'can_work_on_batch' Permission.  But if migration steps 0002 and 0005
    # are run as part of SEPARATE 'manage.py migrate' commands, then step
    # 0002 will create the 'can_work_on_batch' Permission.
    #
    # It appears that the 'can_work_on_batch' Permission is not
    # actually created until ALL migration steps have completed -
    # and if a subsequent step fails, the Permission is never
    # created.
    try:
        Permission.objects.get(codename='can_work_on_batch')
    except ObjectDoesNotExist:
        Permission.objects.create(
            codename='can_work_on_batch',
            content_type=get_content_type(Batch),
            name='Can work on Tasks for this Batch',
        )

    # We use only() to circumvent a Catch-22 where calling Project.objects.all()
    # from this migration fails because Django tries to populate fields that
    # are not added to the database until later migrations:
    #   https://github.com/hltcoe/turkle/issues/136
    for project in Project.objects.all().only('id', 'custom_permissions', 'login_required'):
        project.copy_permissions_to_batches()


class Migration(migrations.Migration):

    dependencies = [
        ('turkle', '0005_batch_published'),
    ]

    operations = [
        migrations.RunPython(copy_project_settings_to_batch),
    ]
