from django.shortcuts import get_object_or_404
from rest_framework.decorators import api_view, permission_classes
from rest_framework.generics import get_object_or_404
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response

from vbv_lernwelt.core.serializers import UserSerializer
from vbv_lernwelt.course.models import Course, CourseSessionUser
from vbv_lernwelt.course_session_group.models import CourseSessionGroup
from vbv_lernwelt.iam.permissions import can_view_profile
from vbv_lernwelt.learning_mentor.models import LearningMentor
from vbv_lernwelt.media_files.models import UserImage


@api_view(["GET", "PUT"])
def me_user_view(request):
    if not request.user.is_authenticated:
        return Response(status=403)

    context = {"langauge": request.user.language}

    if request.method == "GET":
        return Response(UserSerializer(request.user, context=context).data)

    if request.method == "PUT":
        serializer = UserSerializer(
            request.user, data=request.data, partial=True, context=context
        )
        if serializer.is_valid():
            serializer.save()
            return Response(UserSerializer(request.user).data)
        else:
            return Response(serializer.errors, status=400)

    return Response(status=400)


@api_view(["GET"])
@permission_classes([IsAuthenticated])
def get_cockpit_type(request, course_id: int):
    course = get_object_or_404(Course, id=course_id)

    is_mentor = LearningMentor.objects.filter(
        mentor=request.user, course=course
    ).exists()

    is_expert = CourseSessionUser.objects.filter(
        user=request.user,
        course_session__course=course,
        role=CourseSessionUser.Role.EXPERT,
    ).exists()

    is_supervisor = CourseSessionGroup.objects.filter(
        course_session__course=course, supervisor=request.user
    ).exists()

    if is_mentor:
        cockpit_type = "mentor"
    elif is_expert or is_supervisor:
        cockpit_type = "expert"
    else:
        cockpit_type = None

    return Response({"type": cockpit_type})


@api_view(["GET"])
@permission_classes([IsAuthenticated])
def get_profile(request, course_session_id: int, user_id: str):
    course_session_user = get_object_or_404(
        CourseSessionUser, course_session_id=course_session_id, user_id=user_id
    )

    if not can_view_profile(request.user, course_session_user):
        return Response(status=403)

    return Response(UserSerializer(course_session_user.user).data)


@api_view(["POST"])
@permission_classes([IsAuthenticated])
def post_avatar(request):
    if "file" not in request.FILES:
        return Response(status=400)

    request.user.avatar = UserImage.objects.create(
        file=request.FILES["file"],
    )
    request.user.save()

    return Response({"url": request.user.avatar_url})
