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

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


class OwnContentTestCase(TestCase):
    def setUp(self):
        self.module = ModuleFactory()
        self.chapter = Chapter(title='Hello')
        self.module.add_child(instance=self.chapter)
        create_users()
        content_block = ContentBlock(title='bla', slug='bla')
        self.chapter_id = to_global_id('ChapterNode', self.chapter.id)
        self.chapter.specific.add_child(instance=content_block)
        self.user = User.objects.get(username='teacher')
        school_class2 = SchoolClass.objects.get(name='second_class')
        school_class2.users.add(self.user)
        school_class2.save()

        request = RequestFactory().get('/')
        request.user = self.user

        self.client = Client(schema=schema, context_value=request)

    def test_custom_content_blocks(self):
        self.assertEqual(self.user.school_classes.count(), 2)
        chapterQuery = """
        query ChapterQuery($id: ID!) {
          chapter(id: $id) {
            id
            title
            contentBlocks {
              id
              title
            }
          }
        }
        """
        result = self.client.execute(chapterQuery, variables={
            "id": self.chapter_id
        })
        self.assertIsNone(result.get('errors'))
        self.assertEqual(len(result.get('data').get('chapter').get('contentBlocks')), 1)

        custom_content_block = ContentBlock(title='own', slug='own', user_created=True, owner=self.user)
        self.chapter.specific.add_child(instance=custom_content_block)
        result = self.client.execute(chapterQuery, variables={
            "id": self.chapter_id
        })
        self.assertEqual(len(result.get('data').get('chapter').get('contentBlocks')), 2)

        for school_class in self.user.school_classes.all():
            custom_content_block.visible_for.add(school_class)

        result = self.client.execute(chapterQuery, variables={
            "id": self.chapter_id
        })
        self.assertEqual(len(result.get('data').get('chapter').get('contentBlocks')), 2)

