from typing import Set

from django.contrib.postgres.aggregates import ArrayAgg
from django.db import models

from lms.core.visibility.services import available_for_user


class CourseGroupManager(models.Manager):
    def get_queryset(self):
        return super().get_queryset().select_related('course')


class CourseVisibilityManager(models.Manager):
    def unavailable_for(self, user) -> Set[int]:
        """
        Возвращает список id курсов, недоступных пользователю

        :param user: пользователь
        :return:
        """
        course_ids = set()
        course_visibility_group_queryset = (
            self.get_queryset()
            .values('rules_hash', 'parameters', 'formula')
            .annotate(course_ids=ArrayAgg('course_id'))
        )
        for group in course_visibility_group_queryset:
            if not available_for_user(user=user, parameters=group['parameters'], formula=group['formula']):
                course_ids.update(group['course_ids'])

        return course_ids
