"""This module holds the test cases for the workshops-related api views"""

import json

from django.core.urlresolvers import reverse

from mtp.apps.api.tests.test_cases import APITestCase
from mtp.apps.workshops.models import WorkshopStepQuestion, WorkshopStepQuestionUserAnswer
from mtp.apps.workshops.tests.test_cases import BaseWorkshopTestCase


class WorkshopSaveAnswersApiTestCase(BaseWorkshopTestCase, APITestCase):
    """Test case for the ``quiz_save`` api route"""

    @classmethod
    def setUpTestData(cls):
        """Set up the test data"""

        super().setUpTestData()

        cls.answers_save_url = reverse('api:quiz-save', kwargs={'user_uuid': cls.trainee.pk})

    def test_quiz_save_should_save_the_users_answers(self):
        """Test that the route should correctly save the users'answers"""

        # The user don't have any answers
        self.assertEqual(
            WorkshopStepQuestionUserAnswer.objects.filter(user=self.trainee).count(),
            0
        )

        # The "serialized" users answers (sic)
        users_answer_data = {
            'data': [
                {
                    'question_id': question.pk,
                    'text': '',
                    'answer_id': question.answers.first().pk
                }
                for question in self.workshop.steps.instance_of(WorkshopStepQuestion)
            ]
        }

        response = self.client.post(
            self.answers_save_url,
            {
                'json': json.dumps(users_answer_data),
                'session_id': self.training_session.pk
            }
        )

        # Since the response is empty (sic)...
        self.assertEqual(response.status_code, 200)

        # Check the answers was saved
        self.assertEqual(
            WorkshopStepQuestionUserAnswer.objects.filter(user=self.trainee).count(),
            2
        )
