# -*- coding: utf-8 -*-
#
# ITerativ GmbH
# http://www.iterativ.ch/
#
# Copyright (c) 2019 ITerativ GmbH. All rights reserved.
#
# Created on 2019-04-09
# @author: chrigu <christian.cueni@iterativ.ch>
from django.test import RequestFactory, TestCase
from graphene.test import Client

from api.schema import schema
from api.utils import get_graphql_query
from core.factories import UserFactory
from users.factories import SchoolClassFactory
from users.models import SchoolClassMember


class MySchoolClasses(TestCase):
    def setUp(self):
        self.user = UserFactory(username='aschi')
        self.another_user = UserFactory(username='pesche')
        self.class1 = SchoolClassFactory(users=[self.user, self.another_user])
        self.class2 = SchoolClassFactory(users=[self.user])
        self.class3 = SchoolClassFactory(users=[self.another_user])
        self.inactive_class = SchoolClassFactory(users=[self.user])

        inactive_member = SchoolClassMember.objects.get(school_class=self.inactive_class)
        inactive_member.active = False
        inactive_member.save()

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

    def test_user_sees_her_classes(self):
        query = '''
            query  {
              me {
                schoolClasses {
                  edges {
                    node {
                      id
                      name
                      members {
                        id
                        firstName
                        lastName                
                        isTeacher
                      }
                    }
                  }
                }
              }
            }
        '''

        result = self.client.execute(query)
        self.assertIsNone(result.get('errors'))

        classes = result.get('data').get('me').get('schoolClasses').get('edges')
        self.assertEqual(len(classes), 2)

        for school_class in classes:
            if school_class.get('name') == self.class1:
                self.assertEqual(len(school_class.get('node')), 2)
            elif school_class.get('name') == self.class2:
                self.assertEqual(len(school_class.get('node')), 1)
            elif school_class.get('name') == self.class2:
                self.fail('MySchoolClassTest:test_user_sees_her_classes: Class should not be in response')

    def test_old_classes(self):
        query = get_graphql_query('oldClasses.gql')

        result = self.client.execute(query)

        old_classes = result.get('data').get('me').get('oldClasses').get('edges')
        self.assertEqual(len(old_classes), 1)
