"""This module contains the test cases for the metaplans-related views of the api"""

import json

from django.core.urlresolvers import reverse

from mtp.apps.common.tests.test_cases import MTPTestCase
from mtp.apps.metaplans.factories import MetaplanFactory
from mtp.apps.metaplans.models import Metaplan


class MetaplanApiTestCase(MTPTestCase):
    """ Tests Metaplan API. """

    @classmethod
    def setUpTestData(cls):
        super().setUpTestData()

        cls.metaplan = MetaplanFactory()

        cls.new_metaplan_data = {
            'title': 'test_metaplan_sample',
            'data': [{
                'msg': 'text_of_proposition-1',
                'type': '0',
                'user_id': cls.trainee.id
            }, {
                'msg': 'text_of_proposition-2',
                'type': '2',
                'user_id': cls.trainees[1].id
            }]
        }

    def test_metaplan_save(self):
        """ Test the save of metaplan. """
        metaplan_count = Metaplan.objects.count()

        url = reverse('api:metaplan-save', kwargs={'user_uuid': self.trainee.id})
        response = self.client.post(
            url,
            {
                'session_id': self.training_session.id,
                'json': json.dumps(self.new_metaplan_data)
            }
        )

        self.assertEqual(response.status_code, 200)
        self.assertEqual(Metaplan.objects.count(), metaplan_count + 1)  # A new Metaplan is created

        data = json.loads(response.content.decode('utf-8'))
        metaplan = Metaplan.objects.get(id=data.get('id'))

        self.assertEqual(metaplan.propositions.count(), 2)

    def test_metaplan_save_already_exists(self):
        """ Test the save of metaplan already exists. """
        url = reverse('api:metaplan-save',
                      kwargs={
                        'user_uuid': self.trainee.id,
                        'metaplan_uuid': self.metaplan.id
                      })
        response = self.client.post(
            url,
            {
                'session_id': self.training_session.id,
                'json': json.dumps(self.new_metaplan_data)
            }
        )

        self.assertEqual(response.status_code, 200)

        self.assertEqual(self.metaplan.propositions.count(), 2)
