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

from api.schema_public import schema
from core.factories import UserFactory
from users.models import Role


class BetaLoginTests(TestCase):
    def setUp(self):
        self.user = UserFactory(username='aschi@iterativ.ch', email='aschi@iterativ.ch')
        self.teacher_role = Role.objects.create(key=Role.objects.TEACHER_KEY, name="Teacher Role")

        request = RequestFactory().post('/')

        # adding session
        middleware = SessionMiddleware()
        middleware.process_request(request)
        request.session.save()
        self.client = Client(schema=schema, context_value=request)

    def make_login_mutation(self, username, password):
        mutation = '''
            mutation BetaLogin($input: BetaLoginInput!){
              betaLogin(input: $input) {
                success
              }
            }
        '''

        return self.client.execute(mutation, variables={
            'input': {
                'usernameInput': username,
                'passwordInput': password
            }
        })

    def test_user_can_login(self):
        password = 'test123'
        self.user.set_password(password)
        self.user.save()

        result = self.make_login_mutation(self.user.email, password)
        self.assertTrue(result.get('data').get('betaLogin').get('success'))
        self.assertTrue(self.user.is_authenticated)

    def test_user_cannot_login_with_invalid_password(self):
        password = 'test123'
        self.user.set_password(password)
        self.user.save()

        result = self.make_login_mutation(self.user.email, 'test1234')
        self.assertEqual(result.get('errors')[0].get('message'), 'invalid_credentials')

