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

from api.schema import schema
from rooms.factories import RoomFactory
from rooms.models import Room
from users.models import User, SchoolClass
from users.services import create_users


class RoomDeleteEditPermissionsTestcase(TestCase):
    def setUp(self):
        create_users()
        self.teacher = User.objects.get(username='teacher')
        self.teacher2 = User.objects.get(username='teacher2')
        self.student = User.objects.get(username='student1')
        school_class = SchoolClass.objects.get(name='skillbox')
        self.room = RoomFactory(school_class=school_class)
        self.mutation = '''
        mutation DeleteRoom($input: DeleteRoomInput!) {
          deleteRoom(input: $input) {
            success
            errors
          }
        }
        '''
        self.variables = {
            'input': {
                'id': to_global_id('RoomNode', self.room.id)
            }
        }

    def test_delete_own_room(self):
        self.assertEqual(Room.objects.count(), 1)
        request = RequestFactory().get('/')
        request.user = self.teacher
        self.client = Client(schema=schema, context_value=request)

        result = self.client.execute(self.mutation, variables=self.variables)

        self.assertIsNone(result.get('errors'))
        self.assertEqual(Room.objects.count(), 0)

    def test_delete_room_as_student(self):
        self.assertEqual(Room.objects.count(), 1)
        request = RequestFactory().get('/')
        request.user = self.student
        self.client = Client(schema=schema, context_value=request)

        result = self.client.execute(self.mutation, variables=self.variables)

        self.assertIsNotNone(result.get('errors'))
        self.assertEqual(Room.objects.count(), 1)

    def test_delete_room_of_other_class(self):
        self.assertEqual(Room.objects.count(), 1)
        request = RequestFactory().get('/')
        request.user = self.teacher2
        self.client = Client(schema=schema, context_value=request)

        result = self.client.execute(self.mutation, variables=self.variables)

        self.assertIsNotNone(result.get('errors'))
        self.assertEqual(Room.objects.count(), 1)
