import itertools

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

from vbv_lernwelt.feedback.models import FeedbackResponse

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_id):
    feedbacks = FeedbackResponse.objects.filter(
        course_session__course_id=course_id, circle__expert__user=request.user
    ).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_id, circle_id):
    feedbacks = FeedbackResponse.objects.filter(
        course_session__course_id=course_id,
        circle__expert__user=request.user,
        circle_id=circle_id,
    ).order_by("created_at")

    # I guess this is ok for the üK case
    feedback_data = {"amount": len(feedbacks), "questions": {}}

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

    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)
