"""This module holds the api-related views of the ``workshops`` api"""

import json

from collections import defaultdict

from django.contrib.auth import get_user_model
from django.http import HttpResponse
from django.shortcuts import get_object_or_404
from django.views.decorators.csrf import csrf_exempt

from rest_framework import status

from mtp.apps.api.constants import EMPTY_HTTP_RESPONSE
from mtp.apps.trainings.models import TrainingSession

from ..models import WorkshopStepQuestion, WorkshopStepQuestionAnswer


@csrf_exempt
def quiz_save(request, user_uuid, session_uuid=None):
    """Abandon hope all ye who enter here"""

    # json = {
    #     'data': [
    #         {'question_id': '0d70ff06-35da-11e3-b295-b827eb2c2ec6',
    #          'text': '',
    #          'answer_id': '25fbfdfa-35da-11e3-b295-b827eb2c2ec6'},
    #         {'question_id': '0d70ff06-35da-11e3-b295-b827eb2c2ec6',
    #          'text': '',
    #          'answer_id': '26132692-35da-11e3-b295-b827eb2c2ec6'},
    #         {'question_id': '3ae3fa60-35da-11e3-8fcc-b827eb2c2ec6',
    #          'text': 'test open question',
    #          'answer_id': ''},
    #         {'question_id': '46eff7a0-35da-11e3-b295-b827eb2c2ec6',
    #          'text': '',
    #          'answer_id': '62622d5a-35da-11e3-b295-b827eb2c2ec6'}
    #     ]
    # }

    user = get_object_or_404(get_user_model(), pk=user_uuid)
    json_ = request.POST['json']
    data = json.loads(json_)['data']

    if session_uuid:
        session = get_object_or_404(TrainingSession, pk=session_uuid)
    else:
        session = get_object_or_404(TrainingSession, pk=request.POST.get('session_id', None))

    answers_by_question = defaultdict(list)
    for element in data:

        try:
            answer = WorkshopStepQuestionAnswer.objects.get(pk=element['answer_id'])
        except (WorkshopStepQuestionAnswer.DoesNotExist, KeyError):
            answer = (element.get('text') or '').strip()

            # If the provided text is empty or null, we jump to the next element
            if not answer:
                continue

        answers_by_question[element['question_id']].append(answer)

    for question_id in answers_by_question:

        question = get_object_or_404(WorkshopStepQuestion, pk=question_id)

        try:
            question.save_user_answers(
                user,
                session,
                answers_by_question[question_id]
            )
        except TypeError:  # When we try to save many answers for a single choice question
            return HttpResponse(status=status.HTTP_403_FORBIDDEN)

    return EMPTY_HTTP_RESPONSE
