"""This module holds the tests for the views of the ``cms`` app"""

from django.conf import settings
from django.core.urlresolvers import reverse

from django_discover.factories import DiscoverItemFactory
from django_discover.models import DiscoverItem

from mtp.apps.common.tests.test_cases import MTPTestCase
from mtp.apps.questionnaires.models import Quiz


class CMSViewTestCase(MTPTestCase):
    """Test cases for the views of the ``cms`` app"""

    def setUp(self):
        """Login as an admin"""

        super().setUp()

        self.login_as_admin()

    def test_cms_index_view_should_work(self):
        """Test that the cms ``Index`` view is working correctly"""

        response = self.client.get(reverse('cms:index'))
        self.assertEqual(response.status_code, 200)

    def test_cms_index_view_should_contains_ordered_discover_items(self):
        """Test that the index should contains the ordered discover items"""

        # Create 3 discover items
        important_item = DiscoverItemFactory(
            language=settings.DEFAULT_NATURAL_LANGUAGE,
            tag=DiscoverItem.TAG_CHOICES.IMPORTANT
        )
        new_item = DiscoverItemFactory(
            language=settings.DEFAULT_NATURAL_LANGUAGE,
            tag=DiscoverItem.TAG_CHOICES.NEW
        )
        item = DiscoverItemFactory(language=settings.DEFAULT_NATURAL_LANGUAGE)

        response = self.client.get(reverse('cms:index'))
        self.assertEqual(
            list(response.context['discover_items']),
            [
                important_item,
                new_item,
                item
            ]
        )


class DiscoverItemDetailView(MTPTestCase):
    """Test case for the ``DiscoverItemDetailView`` view"""

    @classmethod
    def setUpTestData(cls):
        """Create some ``DiscoverItems`` to test against"""

        super().setUpTestData()

        cls.default_discover_item = DiscoverItemFactory(
            slug='default_discover_item',
            language=settings.DEFAULT_NATURAL_LANGUAGE
        )

        cls.activity_discover_item = DiscoverItemFactory(
            slug='quiz',
            language=settings.DEFAULT_NATURAL_LANGUAGE
        )

    def setUp(self):
        """Login as an admin"""

        super().setUp()

        self.login_as_admin()

    def test_view_should_output_404_if_no_matching_discover_item_were_found(self):
        """Test that the view should output a 404 if no matching items were found"""

        response = self.client.get(
            reverse('cms:discover_detail', kwargs={'slug': 'not-a-slug'})
        )

        self.assertEqual(response.status_code, 404)

    def test_view_should_work_if_default_discover_item(self):
        """Test that the view should work if passing a slug from a discover item"""

        response = self.client.get(
            reverse('cms:discover_detail', kwargs={'slug': self.default_discover_item.slug})
        )

        self.assertEqual(response.status_code, 200)
        self.assertEqual(
            response.context['discoveritem'],
            self.default_discover_item
        )

    def test_view_should_fallback_to_default_language_discover_item(self):
        """Test that the view should fallback to the default language"""

        # Set the language to "fr"
        self.client.cookies.load({settings.LANGUAGE_COOKIE_NAME: 'fr'})

        response = self.client.get(
            reverse('cms:discover_detail', kwargs={'slug': self.default_discover_item.slug})
        )

        self.assertEqual(response.status_code, 200)

        # Because there is no discover item available for french, we get the english one
        self.assertEqual(
            response.context['discoveritem'],
            self.default_discover_item
        )

        # Create the french one
        french_discover_item = DiscoverItemFactory(
            slug='default_discover_item',
            language='fr'
        )

        response = self.client.get(
            reverse('cms:discover_detail', kwargs={'slug': self.default_discover_item.slug})
        )

        # Now that it exists, we should get the french one
        self.assertEqual(
            response.context['discoveritem'],
            french_discover_item
        )

    def test_view_should_add_the_contextual_discover_item_url_to_the_context(self):
        """Test that the view should add the discover item url to the context if applicable"""

        # Testing from the index page...
        response = self.client.get(
            reverse(
                'cms:discover_detail',
                kwargs={'slug': self.activity_discover_item.slug},
            ),
            HTTP_REFERER=reverse('cms:index')
        )

        self.assertEqual(response.status_code, 200)

        # ...We should have a link to the private library (and the "modal-url" param)
        self.assertEqual(
            response.context['discover_link_url'],
            '%s?modal-url=%s' % (
                reverse('trainings:activities-private-library'),
                Quiz.get_create_url(),
            )
        )

        # Testing from the private library page...
        response = self.client.get(
            reverse(
                'cms:discover_detail',
                kwargs={'slug': self.activity_discover_item.slug},
            ),
            HTTP_REFERER=reverse('trainings:activities-private-library')
        )

        self.assertEqual(response.status_code, 200)

        # ...We should have a link to the private library (and the "modal-url" param)
        self.assertEqual(
            response.context['discover_link_url'],
            '%s?modal-url=%s' % (
                reverse('trainings:activities-private-library'),
                Quiz.get_create_url(),
            )
        )

        # Testing from the training detail url page...
        training_url = reverse('trainings:training-detail', kwargs={
            'training_uuid': self.admin_training.id
        })

        response = self.client.get(
            reverse(
                'cms:discover_detail',
                kwargs={'slug': self.activity_discover_item.slug},
            ),
            HTTP_REFERER=training_url
        )

        self.assertEqual(response.status_code, 200)

        # ...We should have a link to the private library (and the "modal-url" param)
        self.assertEqual(
            response.context['discover_link_url'],
            '%s?modal-url=%s' % (
                training_url,
                Quiz.get_training_create_url(self.admin_training),
            )
        )
