new_contents: # Generated by Django 2.1.7 on 2019-02-25 12:28
  
  from django.db import migrations
  from django.contrib.auth.models import User, Group
  from django.conf import settings
  from guardian.shortcuts import assign_perm, remove_perm
  
  # Permission types
  PERMISSION_TYPES = ("view", "add", "change", "delete")
  
  # Existing annotation (name, codename) as of annotations.0001_initial
  ANNOTATION_CODENAMES = (
      ("BooleanClassificationAnnotation", "booleanclassificationannotation"),
      ("CoordinateListAnnotation", "coordinatelistannotation"),
      ("IntegerClassificationAnnotation", "integerclassificationannotation"),
      ("LandmarkAnnotationSet", "landmarkannotationset"),
      ("MeasurementAnnotation", "measurementannotation"),
      ("PolygonAnnotationSet", "polygonannotationset"),
      ("SingleLandmarkAnnotation", "singlelandmarkannotation"),
      ("SinglePolygonAnnotation", "singlepolygonannotation"),
      ("ETDRSGridAnnotation", "etdrsgridannotation"),
  )
  
  
  def change_retina_permissions(apps, change_permission_func):
      retina_admins = Group.objects.get(name=settings.RETINA_ADMINS_GROUP_NAME)
      for (annotation_name, annotation_codename) in ANNOTATION_CODENAMES:
          # Change user level object permissions to owners of annotations
          Annotation = apps.get_model('annotations', annotation_name)
          for annotation in Annotation.objects.all():
              if annotation_name.startswith('single'):
                  owner = annotation.annotation_set.grader
              else:
                  owner = annotation.grader
  
              if owner.groups.filter(name=settings.RETINA_GRADERS_GROUP_NAME).exists():
                  for permission_type in PERMISSION_TYPES:
                      change_permission_func(
                          f"annotations.{permission_type}_{annotation_codename}",
                          owner,
                          annotation
                      )
  
          # Change group level permissions
          for permission_type in PERMISSION_TYPES:
              change_permission_func(
                  f"annotations.{permission_type}_{annotation_codename}",
                  retina_admins,
              )
  
  
  def set_retina_permissions_forward(apps, schema_editor):
      change_retina_permissions(apps, assign_perm)
  
  
  def set_retina_permissions_backward(apps, schema_editor):
      change_retina_permissions(apps, remove_perm)
  
  
  class Migration(migrations.Migration):
  
      dependencies = [
          ("retina_core", "0001_initial"),
          migrations.swappable_dependency(settings.AUTH_USER_MODEL),
          ("annotations", "0001_initial"),
      ]
  
      operations = [
          migrations.RunPython(
              set_retina_permissions_forward, set_retina_permissions_backward
          )
      ]
  
subject: Add migration for setting retina annotation permissions