# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2018-07-31 20:46
from __future__ import unicode_literals

from django.db import migrations


def _set_team_perms(apps, schema_editor):
    db_alias = schema_editor.connection.alias

    Team = apps.get_model('multidb_account', 'Team')
    AssessmentTopCategory = apps.get_model('multidb_account', 'AssessmentTopCategory')
    AssessmentTopCategoryPermission = apps.get_model('multidb_account', 'AssessmentTopCategoryPermission')

    for team in Team.objects.using(db_alias).all():
        for athlete in team.athletes.using(db_alias).all():
            for coach in team.coaches.using(db_alias).all():
                for top_category in AssessmentTopCategory.objects.using(db_alias).all():

                    # we want all top categories granted by default to Coaches
                    # we want category (general-leadership(id=10001)) granted by default to athlete
                    coach_has_access = True
                    athlete_has_access = top_category.id == 10001

                    # Grant new coach permission to assess athletes
                    AssessmentTopCategoryPermission.objects.using(db_alias).get_or_create(
                        assessed=athlete.assessed,
                        assessor=coach.assessor,
                        assessment_top_category=top_category,
                        defaults={
                            'assessor_has_access': coach_has_access,
                        },
                    )

                    # Grant athletes permission to assess new coach
                    if athlete.assessor and coach.assessed:
                        AssessmentTopCategoryPermission.objects.using(db_alias).get_or_create(
                            assessed=coach.assessed,
                            assessor=athlete.assessor,
                            assessment_top_category=top_category,
                            defaults={
                                'assessor_has_access': athlete_has_access,
                            },
                        )


class Migration(migrations.Migration):
    dependencies = [
        ('multidb_account', '0049_basecustomuser_new_dashboard'),
    ]

    operations = [
        migrations.RunPython(_set_team_perms),
    ]
