from vbv_lernwelt.core.models import User
from vbv_lernwelt.course.models import CourseSession, CourseSessionUser
from vbv_lernwelt.course_session_group.models import CourseSessionGroup
from vbv_lernwelt.learnpath.models import LearningSequence


def has_course_access_by_page_request(request, obj):
    return has_course_access(request.user, obj.specific.get_course().id)


def has_course_access(user, course_id):
    if user.is_superuser:
        return True

    if CourseSessionGroup.objects.filter(
        course_session__course_id=course_id, supervisor=user
    ).exists():
        return True

    return CourseSessionUser.objects.filter(
        course_session__course_id=course_id, user=user
    ).exists()


def has_course_session_access(user, course_session_id: int):
    if user.is_superuser:
        return True

    return CourseSessionUser.objects.filter(
        course_session_id=course_session_id, user=user
    ).exists()


def is_course_session_expert(user, course_session_id: int):
    if user.is_superuser:
        return True

    is_supervisor = CourseSessionGroup.objects.filter(
        supervisor=user, course_session__id=course_session_id
    ).exists()

    is_expert = CourseSessionUser.objects.filter(
        course_session_id=course_session_id,
        user=user,
        role=CourseSessionUser.Role.EXPERT,
    ).exists()

    return is_supervisor or is_expert


def course_sessions_for_user_qs(user):
    if user.is_superuser:
        return CourseSession.objects.all()

    course_sessions = CourseSession.objects.filter(coursesessionuser__user=user)

    return course_sessions


def is_circle_expert(user, course_session_id: int, learning_sequence_id: int) -> bool:
    if user.is_superuser:
        return True

    try:
        learning_sequence = LearningSequence.objects.get(id=learning_sequence_id)
    except LearningSequence.DoesNotExist:
        return False

    circle_id = learning_sequence.get_parent().circle.id

    return CourseSessionUser.objects.filter(
        course_session_id=course_session_id,
        user=user,
        role=CourseSessionUser.Role.EXPERT,
        expert__id=circle_id,
    ).exists()


def can_view_course_session_group_statistics(
    user: User, group: CourseSessionGroup
) -> bool:
    if user.is_superuser:
        return True

    return user in group.supervisor.all()


def can_view_course_session_progress(user: User, course_session: CourseSession) -> bool:
    return CourseSessionUser.objects.filter(
        course_session=course_session,
        user=user,
        role=CourseSessionUser.Role.MEMBER,
    ).exists()


def can_view_course_session(user: User, course_session: CourseSession) -> bool:
    if user.is_superuser:
        return True

    if CourseSessionGroup.objects.filter(
        course_session=course_session, supervisor=user
    ).exists():
        return True

    return CourseSessionUser.objects.filter(
        course_session=course_session,
        user=user,
    ).exists()
