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

from api.schema import schema
from core.factories import UserFactory
from core.tests.base_test import SkillboxTestCase
from rooms.factories import RoomEntryFactory, RoomFactory
from rooms.models import RoomEntry
from users.factories import SchoolClassFactory

ADD_ROOM_ENTRY_MUTATION = """
fragment RoomEntryParts on RoomEntryNode {
  id
  slug
  title
  contents
  author {
    id
    firstName
    lastName
    avatarUrl
  }
}


mutation AddRoomEntry($input: AddRoomEntryInput!){
  addRoomEntry(input: $input) {
    roomEntry {
      ...RoomEntryParts
    }
    errors

  }
}        
        """


class RoomEntryMutationsTestCase(SkillboxTestCase):
    def setUp(self):
        self.user = UserFactory(username="aschi")
        self.another_user = UserFactory(username="pesche")
        self.yet_another_user = UserFactory(username="hansueli")
        s = SchoolClassFactory(users=[self.user, self.another_user])
        s2 = SchoolClassFactory(users=[self.yet_another_user])
        # self.room_entry = RoomEntryFactory(author=self.user, room=RoomFactory(school_class=s))
        self.room_entry = RoomEntryFactory(author=self.user, room__school_class=s)
        self.room = self.room_entry.room
        self.first_school_class = s

        request = RequestFactory().get("/")
        request.user = self.user
        self.client = Client(schema=schema, context_value=request)

    def test_delete_room_entry(self):
        self.assertEqual(RoomEntry.objects.count(), 1)

        mutation = """
        mutation DeleteRoomEntry($input: DeleteRoomEntryInput!) {
              deleteRoomEntry(input: $input) {
                success
                errors
              }
            }
        """

        result = self.client.execute(
            mutation, variables={"input": {"slug": self.room_entry.slug}}
        )
        self.assertIsNone(result.get("errors"))
        self.assertEqual(RoomEntry.objects.count(), 0)

    def test_delete_room_not_owner(self):
        self.assertEqual(RoomEntry.objects.count(), 1)
        mutation = """
                mutation DeleteRoomEntry($input: DeleteRoomEntryInput!) {
                      deleteRoomEntry(input: $input) {
                        success
                        errors
                      }
                    }
                """

        request = RequestFactory().get("/")
        request.user = self.another_user
        client = Client(schema=schema, context_value=request)

        result = client.execute(
            mutation,
            variables={
                "input": {"id": to_global_id("RoomEntryNode", self.room_entry.pk)}
            },
        )

        self.assertIsNotNone(result.get("errors"))
        self.assertEqual(RoomEntry.objects.count(), 1)

    def test_update_room_entry_not_owner_but_same_class(self):
        self.assertEqual(RoomEntry.objects.count(), 1)
        mutation = """
                mutation UpdateRoomEntry($input: UpdateRoomEntryInput!){
                  updateRoomEntry(input: $input) {
                    roomEntry {
                      title
                      author {
                        firstName
                      }
                    }
                    errors
                  }
                }
                """

        request = RequestFactory().get("/")
        request.user = self.another_user
        client = Client(schema=schema, context_value=request)

        new_title = "new title, Alte!"

        result = client.execute(
            mutation,
            variables={
                "input": {
                    "roomEntry": {
                        "id": to_global_id("RoomEntryNode", self.room_entry.pk),
                        "title": new_title,
                    }
                }
            },
        )

        entry = RoomEntry.objects.get(pk=self.room_entry.pk)
        self.assertIsNotNone(result.get("errors"))
        self.assertEqual(entry.title, self.room_entry.title)

    def test_update_room_entry_not_owner_from_other_class(self):
        self.assertEqual(RoomEntry.objects.count(), 1)
        mutation = """
                mutation UpdateRoomEntry($input: UpdateRoomEntryInput!){
                  updateRoomEntry(input: $input) {
                    roomEntry {
                      title
                      author {
                        firstName
                      }
                    }
                    errors
                  }
                }
                """

        request = RequestFactory().get("/")
        request.user = self.yet_another_user
        client = Client(schema=schema, context_value=request)

        new_title = "new title, Alte!"

        result = client.execute(
            mutation,
            variables={
                "input": {
                    "roomEntry": {
                        "id": to_global_id("RoomEntryNode", self.room_entry.pk),
                        "title": new_title,
                    }
                }
            },
        )

        entry = RoomEntry.objects.get(pk=self.room_entry.pk)
        self.assertIsNotNone(result.get("errors"))
        self.assertEqual(entry.title, self.room_entry.title)

    def test_add_room_entry_not_owner_from_other_class(self):
        self.assertEqual(RoomEntry.objects.count(), 1)
        # input:
        # title = graphene.String(required=True)
        # contents = graphene.List(ContentElementInput)
        # room = graphene.ID(required=True)
        room_entry = {"title": "Bad Actor!", "roomSlug": self.room.slug}

        result = self.get_client(self.yet_another_user).execute(
            ADD_ROOM_ENTRY_MUTATION, variables={"input": {"roomEntry": room_entry}}
        )
        self.assertIsNotNone(result.errors)
        self.assertTrue("message" in result.errors[0])
        self.assertEqual(result.errors[0]["message"], "You are in the wrong class")

    def test_add_room_entry(self):
        self.assertEqual(RoomEntry.objects.count(), 1)
        text_block = {"type": "text_block", "value": {"text": "<p>some text</p>"}}
        subtitle_block = {"type": "subtitle", "value": {"text": "A subtitle"}}
        room_entry = {
            "title": "A room entry",
            "roomSlug": self.room.slug,
            "contents": [text_block, subtitle_block],
        }
        result = self.get_client(self.user).execute(
            ADD_ROOM_ENTRY_MUTATION, variables={"input": {"roomEntry": room_entry}}
        )
        self.assertIsNone(result.errors)
        room_entry_data = result.data.get("addRoomEntry").get("roomEntry")
        contents = room_entry_data.get("contents")
        self.assertEqual(len(contents), 2)
        text, subtitle = contents
        self.assertEqual(text.get("type"), "text_block")
        self.assertEqual(subtitle.get("type"), "subtitle")
        self.assertEqual(RoomEntry.objects.count(), 2)
