"""Test cases for the views of the ``metaplans`` app"""

from django.core.urlresolvers import reverse
from django.test import override_settings

from ..factories import MetaplanFactory

from .test_cases import MetaplanTestCase


class MetaplanViewsTestCase(MetaplanTestCase):
    """Test cases for the views of the ``Metaplan`` model"""

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

        super().setUpTestData()

        # We will need one metaplan from the template
        cls.metaplan = MetaplanFactory(
            session=cls.training_session
        )

        cls.metaplan_routes = [
            reverse('metaplans:list_by_session', kwargs={'session_id': cls.training_session.pk}),
            reverse('metaplans:create', kwargs={'session_id': cls.training_session.pk}),
            reverse('metaplans:update', kwargs={'pk': cls.metaplan.pk}),
            reverse('metaplans:delete', kwargs={'pk': cls.metaplan.pk}),
            reverse('metaplans:detail', kwargs={'pk': cls.metaplan.pk}),
            reverse('metaplans:export', kwargs={'pk': cls.metaplan.pk}),
            reverse('metaplans:create_proposition', kwargs={
                'metaplan_id': cls.metaplan.pk
            })
        ]

    def test_all_routes(self):
        """Test all the metaplan related routes"""

        self.login_as_trainer()

        for route in self.metaplan_routes:
            with self.subTest(route=route):
                response = self.client.get(route)
                self.assertEqual(response.status_code, 200)

    def test_create_metaplan_not_allowed_on_closed_session(self):
        """A metaplan can not be created on a closed session"""

        with override_settings(INSTANCE_IS_MASTER=True):
            self.training_session.close()

        create_url = reverse(
            'metaplans:create',
            kwargs={'session_id': self.training_session.pk}
        )

        # The GET method for creation should raise 403 on closed session
        response = self.client.get(create_url)
        self.assertEqual(response.status_code, 403)

        # The POST method for creation should raise 403 on closed session
        response = self.client.post(create_url, {})
        self.assertEqual(response.status_code, 403)
