from graphql_relay import to_global_id

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

class GQLRoom:
    def __init__(self, result):
        self.restricted = result.get('restricted')
        self.room_entries = list(map(lambda x: x['node'], result.get('roomEntries').get('edges')))


class TestRoomVisibilityQueryTestCase(SkillboxTestCase):
    def setUp(self) -> None:
        self.createDefault()
        self.room = RoomFactory(school_class=self.school_class, restricted=True)
        self.room_id = to_global_id('RoomNode', self.room.id)
        RoomEntryFactory(room=self.room, author=self.student1)
        RoomEntryFactory(room=self.room, author=self.student2)

        self.query = """
query RoomQuery ($slug: String!) {
    room(slug: $slug) {
        restricted
        roomEntries {
          edges {
            node {
              id
            }
          }
        }
    }
}
        """

    def _test_room(self, user, length, restricted=True):
        res = self.get_client(user).execute(self.query, variables={
            'slug': self.room.slug
        })
        result = GQLResult(res)
        self.assertIsNone(result.errors)
        room = GQLRoom(result.data.get('room'))
        self.assertEqual(room.restricted, restricted)
        self.assertEqual(len(room.room_entries), length)


    def test_restricted_query(self):
        self._test_room(self.teacher, 2)
        self._test_room(self.student1, 1)
        self._test_room(self.student2, 1)

    def test_unrestricted_query(self):
        self.room.restricted = False
        self.room.save()

        self._test_room(self.teacher, 2, False)
        self._test_room(self.student1, 2, False)
        self._test_room(self.student2, 2, False)

        # res = self.get_client().execute(self.query, variables={
        #     'slug': self.room.slug
        # })
        # result = GQLResult(res)
        # self.assertIsNone(result.errors)
        # room = GQLRoom(result.data.get('room'))
        # self.assertTrue(room.restricted)
        # self.assertEqual(len(room.room_entries), 2)
        #
        # res = self.get_client(self.student1).execute(self.query, variables={
        #     'slug': self.room.slug
        # })


