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

from api.schema import schema
from api.utils import get_object, get_graphql_mutation
from books.models import ContentBlock, Chapter
from books.factories import ModuleFactory
from core.factories import UserFactory
from core.management.commands import create_teacher
from notes.factories import ChapterBookmarkFactory, ModuleBookmarkFactory
from objectives.factories import ObjectiveGroupFactory
from objectives.models import Objective
from users.models import User
from users.services import create_users


class ObjectiveOrderTestCase(TestCase):
    def setUp(self):
        create_users()

        self.user = user = User.objects.get(username='teacher')

        self.objective_group = ObjectiveGroupFactory()


        request = RequestFactory().get('/')
        request.user = user

        self.client = Client(schema=schema, context_value=request)

        Objective.objects.create(text='first', group=self.objective_group, order=0)
        Objective.objects.create(text='second', group=self.objective_group, order=1)
        Objective.objects.create(text='third', group=self.objective_group)
        Objective.objects.create(text='fourth', group=self.objective_group)

    def test_objective_order(self):
        query = """
        query ObjectiveGroupQuery($id: ID!) {
          objectiveGroup(id: $id) {
            objectives {
              id
              text
            }
          }
        }
        """

        result = self.client.execute(query, variables={
            'id': to_global_id('ObjectiveGroupNode', self.objective_group.pk)
        })

        self.assertIsNone(result.get('errors'))
        objective_nodes = result.get('data').get('objectiveGroup').get('objectives')

        objective1, objective2, objective3, objective4 = [node for node in objective_nodes]

        self.assertEqual(objective1.get('text'), 'first')
        self.assertEqual(objective2.get('text'), 'second')
        self.assertEqual(objective3.get('text'), 'third')
        self.assertEqual(objective4.get('text'), 'fourth')

