from vbv_lernwelt.course.models import CourseSession, CourseSessionUser
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 CourseSessionUser.objects.filter(
        course_session__course_id=course_id, user=user
    ).exists():
        return True

    return False


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

    if CourseSessionUser.objects.filter(
        course_session_id=course_session_id,
        user=user,
        role=CourseSessionUser.Role.EXPERT,
    ).exists():
        return True

    return False


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

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

    return False
