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

from api.schema import schema
from portfolio.factories import ProjectFactory
from users.factories import SchoolClassFactory
from users.models import User
from users.services import create_users
from api.test_utils import create_client, DefaultUserTestCase
from portfolio.models import Project, ProjectEntry


class ProjectMutationsTestCase(DefaultUserTestCase):
    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')
        self.student2 = User.objects.get(username='student2')
        self.project1 = ProjectFactory(student=self.student)

        self.mutation = '''
            mutation AddProjectEntryMutation($input: AddProjectEntryInput!) {
              addProjectEntry(input: $input) {
                projectEntry {
                  id
                  description
                  created
                }
                errors
              }
            }
        '''

        self.variables = {
            'input': {
                'projectEntry': {
                    'project': to_global_id('ProjectNode', self.project1.id),
                    'description': 'testdescription'
                }
            }
        }

    def test_add_project_entry(self):
        client = create_client(self.student)
        self.assertEqual(ProjectEntry.objects.count(), 0)
        result = client.execute(self.mutation, variables=self.variables)
        self.assertIsNone(result.get('errors'))
        self.assertEqual(ProjectEntry.objects.count(), 1)
        project_entry = ProjectEntry.objects.first()
        self.assertEqual(project_entry.description, 'testdescription')

    def test_should_not_be_able_to_add_entry_as_other_person(self):
        client = create_client(self.student2)
        self.assertEqual(ProjectEntry.objects.count(), 0)
        result = client.execute(self.mutation, variables=self.variables)
        self.assertIsNone(result.get('errors'))
        self.assertEqual(ProjectEntry.objects.count(), 0)
