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 Chapter, ContentBlock
from core.tests.base_test import SkillboxTestCase
from users.models import User, SchoolClass
from users.services import create_users


class OwnContentTestCase(SkillboxTestCase):
    def setUp(self):
        self.module = ModuleFactory()
        self.chapter = Chapter(title='Hello')
        self.module.add_child(instance=self.chapter)
        self.createDefault()
        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
        assert content_block.id is not None
        self.content_block_id = to_global_id('ContentBlockNode', content_block.id)

        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.get_client().execute(chapterQuery, variables={
            "id": self.chapter_id
        })
        self.assertIsNone(result.errors)
        self.assertEqual(len(result.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.get_client().execute(chapterQuery, variables={
            "id": self.chapter_id
        })
        self.assertEqual(len(result.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.get_client().execute(chapterQuery, variables={
            "id": self.chapter_id
        })
        self.assertEqual(len(result.data.get('chapter').get('contentBlocks')), 2)

    def test_mutate_own_content_block(self):
        query = """
        query ContentBlockQuery($id: ID!) {
            contentBlock(id: $id) {
                contents
                title
            }
        } 
        """

        res = self.get_client().execute(query, variables={'id': self.content_block_id})
        self.assertIsNone(res.errors)
        self.assertEqual(res.data['contentBlock']['title'], 'bla')

        mutation = """
        mutation MutateContentBlock($input: MutateContentBlockInput!) {
            mutateContentBlock(input: $input) {
              contentBlock {
                 contents
                 title
              } 
            }
        }
        """

        new_content = {
            'id': '',
            'type': 'text_block',
            'value': {
                'text': 'new text \n a new line'
            }
        }

        variables = {
            'input': {
                'id': self.content_block_id,
                'contentBlock': {
                    'contents': [
                        new_content
                    ],
                    'title': 'new title',
                    'type': 'NORMAL'
                }
            }
        }

        mutation_result = self.get_client().execute(mutation, variables=variables)
        self.assertIsNone(mutation_result.errors)
        content_block = mutation_result.data['mutateContentBlock']['contentBlock']
        self.assertEqual(content_block['title'], 'new title')
        self.assertEqual(content_block['contents'][0]['value']['text'], '<p>new text</p>\n<p>a new line</p>')

        content_with_list = {
            'id': '',
            'type': 'text_block',
            'value': {
                'text': '<ul><li>Hallo</li><li>Velo</li></ul>'
            }
        }
        other_variables = {
            'input': {
                'id': self.content_block_id,
                'contentBlock': {
                    'contents': [
                        content_with_list
                    ],
                    'title': 'title for list content',
                    'type': 'NORMAL'
                }
            }
        }
        list_mutation_result = self.get_client().execute(mutation, variables=other_variables)
        self.assertIsNone(list_mutation_result.errors)
        content_block = list_mutation_result.data['mutateContentBlock']['contentBlock']
        self.assertEqual(content_block['title'], 'title for list content')
        self.assertEqual(content_block['contents'][0]['value']['text'], '<ul><li>Hallo</li><li>Velo</li></ul>')
