from graphql_relay import to_global_id

from core.tests.base_test import SkillboxTestCase
from core.tests.helpers import GQLResult
from rooms.factories import CommentFactory, RoomEntryFactory, RoomFactory



class CommentTestCase(SkillboxTestCase):
    def setUp(self) -> None:
        self.createDefault()
        room = RoomFactory(school_class=self.school_class)
        self.room_entry = RoomEntryFactory(room=room, author=self.teacher)
        self.room_entry_id = to_global_id('RoomEntryNode', self.room_entry.id)
        self.text = 'First!!!'


    def test_add_comment(self):
        room_entry = self.room_entry

        mutation = """
mutation AddComment($input: AddCommentInput!) {
  addComment(input: $input) {
    success
  }
}
"""
        self.assertEqual(room_entry.comments.count(), 0)

        result = self.get_client().execute(mutation, variables={
            'input': {
                'roomEntry': self.room_entry_id,
                'comment': self.text
            }
        })
        self.assertIsNone(result.get('errors'))
        self.assertEqual(room_entry.comments.count(), 1)
        comment = room_entry.comments.first()
        self.assertEqual(comment.text, self.text)
        self.assertEqual(comment.owner.id, self.teacher.id)

    def test_get_comment(self):

        CommentFactory(room_entry=self.room_entry, text=self.text, owner=self.teacher)

        query = """
query CommentsQuery($id: ID!) {
    roomEntry(id: $id) {
        comments {
            edges {
                node {
                    text
                }
            }
        }
    }
}
"""
        result = self.get_client().execute(query, variables={"id": self.room_entry_id})
        self.assertIsNone(result.get('errors'))
        comment_node = result.get('data').get('roomEntry').get('comments').get('edges')[0].get('node')
        self.assertEqual(comment_node['text'], self.text)

    def test_get_comment_for_other_user(self):
        CommentFactory(room_entry=self.room_entry, text=self.text, owner=self.teacher)
        query = """
        query CommentsQuery($id: ID!) {
            roomEntry(id: $id) {
                comments {
                    edges {
                        node {
                            text
                        }
                    }
                }
            }
        }
        """

        result = self.get_client(self.student_second_class).execute(query, variables={"id": self.room_entry_id})
        gql_result = GQLResult(result)
        self.assertIsNone(gql_result.errors)
        self.assertIsNone(gql_result.data.get('roomEntry'))
