import itertools

import structlog
from rest_framework.decorators import api_view
from rest_framework.exceptions import PermissionDenied
from rest_framework.response import Response

from vbv_lernwelt.feedback.models import FeedbackResponse
from vbv_lernwelt.feedback.utils import feedback_users
from vbv_lernwelt.iam.permissions import is_course_session_expert

logger = structlog.get_logger(__name__)

FEEDBACK_FIELDS = [
    "satisfaction",
    "goal_attainment",
    "proficiency",
    "instructor_competence",
    "instructor_respect",
    "instructor_open_feedback",
    "would_recommend",
    "course_positive_feedback",
    "course_negative_feedback",
    "preparation_task_clarity",
]


@api_view(["GET"])
def get_expert_feedbacks_for_course(request, course_session_id):
    if not is_course_session_expert(request.user, course_session_id):
        raise PermissionDenied()

    feedbacks = FeedbackResponse.objects.filter(
        course_session__id=course_session_id,
        submitted=True,
    ).order_by("circle_id")
    circle_count = []

    grouped_feedbacks = itertools.groupby(feedbacks, lambda x: x.circle_id)

    for key, feedbacks in grouped_feedbacks:
        circle_count.append(
            {
                "circle_id": key,
                "count": len(list(feedbacks)),
            }
        )

    return Response(status=200, data=circle_count)


@api_view(["GET"])
def get_feedback_for_circle(request, course_session_id, circle_id):
    if not is_course_session_expert(request.user, course_session_id):
        raise PermissionDenied()

    feedbacks = FeedbackResponse.objects.filter(
        course_session__id=course_session_id,
        submitted=True,
        circle_id=circle_id,
        feedback_user__in=feedback_users(course_session_id),
    ).order_by("created_at")

    feedback_data = {"amount": len(feedbacks), "questions": {}, "feedbackType": None}

    if feedback_data["amount"] == 0:
        return Response(status=200, data=feedback_data)

    feedback_data["feedbackType"] = feedbacks[0].data.get("feedback_type", None)

    for field in FEEDBACK_FIELDS:
        feedback_data["questions"][field] = []

    for feedback in feedbacks:
        for field in FEEDBACK_FIELDS:
            data = feedback.data.get(field, None)
            if data is not None:
                feedback_data["questions"][field].append(data)

    return Response(status=200, data=feedback_data)
