from django.test import TestCase, RequestFactory
from graphene.test import Client
from graphql_relay import to_global_id

from api.schema import schema
from books.factories import ModuleFactory
from books.models import ContentBlock, Chapter
from users.factories import SchoolClassFactory
from users.models import User
from users.services import create_users


class ContentBlocksVisibleForTeachers(TestCase):
    def setUp(self):
        module = ModuleFactory()
        chapter = Chapter(title='Some Chapter')
        module.add_child(instance=chapter)
        create_users()
        teacher = User.objects.get(username='teacher')
        teacher2 = User.objects.get(username='teacher2')
        student = User.objects.get(username='student1')
        school_class = SchoolClassFactory(users=[teacher, teacher2, student])

        default_content_block = ContentBlock(title='default block', slug='default')
        user_content_block = ContentBlock(title='user created', slug='user', user_created=True, owner=teacher)
        chapter.specific.add_child(instance=default_content_block)
        chapter.specific.add_child(instance=user_content_block)

        user_content_block.visible_for.add(school_class)
        user_content_block.save()

        teacher_request = RequestFactory().get('/')
        teacher_request.user = teacher
        self.teacher_client = Client(schema=schema, context_value=teacher_request)

        teacher2_request = RequestFactory().get('/')
        teacher2_request.user = teacher2
        self.teacher2_client = Client(schema=schema, context_value=teacher2_request)

        student_request = RequestFactory().get('/')
        student_request.user = student
        self.student_client = Client(schema=schema, context_value=student_request)

        self.chapter = to_global_id('ChapterNode', chapter.pk)

    def _assert_school_classes(self, query, client):
        result = client.execute(query, variables={
            'id': self.chapter
        })
        self.assertIsNone(result.get('errors'))
        self.assertEqual(len(result.get('data').get('chapter').get('contentBlocks')), 2)

    def test_teacher_created_content_block(self):
        self.assertEqual(ContentBlock.objects.count(), 2)

        query = """
            query ChapterQuery($id: ID!) {
                chapter(id: $id) {
                  contentBlocks {
                    id
                  }
                }
            }
        """

        self._assert_school_classes(query, self.student_client)
        self._assert_school_classes(query, self.teacher_client)
        self._assert_school_classes(query, self.teacher2_client)
