# -*- coding: utf-8 -*-
#
# ITerativ GmbH
# http://www.iterativ.ch/
#
# Copyright (c) 2019 ITerativ GmbH. All rights reserved.
#
# Created on 2019-10-08
# @author: chrigu <christian.cueni@iterativ.ch>
from unittest.mock import patch

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.hep_client import HepClient
from core.tests.mock_hep_data_factory import ME_DATA, VALID_TEACHERS_ORDERS
from users.models import License
from users.models import User, Role, SchoolClass

INVALID_KEY_ME = dict(ME_DATA)

INVALID_KEY_ME['confirmation'] = 'abddddddd'


class RegistrationTests(TestCase):
    def setUp(self):
        request = RequestFactory().post('/')

        Role.objects.create_default_roles()

        self.email = 'sepp@skillbox.iterativ.ch'
        self.first_name = 'Sepp'
        self.last_name = 'Feuz'

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

    def make_register_mutation(self, confirmation_key, user_id):
        mutation = '''
            mutation Registration($input: RegistrationInput!){
              registration(input: $input) {
                success
                message
              }
            }
        '''

        return self.client.execute(mutation, variables={
            'input': {
                'confirmationKey': confirmation_key,
                'userId': user_id
            }
        })

    @patch.object(HepClient, 'customer_activate', return_value="Response")
    @patch.object(HepClient, 'customers_by_id', return_value=ME_DATA)
    @patch.object(HepClient, 'myskillbox_product_for_customer', return_value=None)
    @patch.object(HepClient, 'fetch_admin_token', return_value=b'"AABBCCDDEE**44566"')
    def test_user_can_register_with_valid_confirmation_key_and_no_license(self, admin_mock, customer_by_id_mock,
                                                                          product_mock, customer_mock):

        result = self.make_register_mutation('CONFIRMATION_KEY', 1)

        self.assertTrue(result.get('data').get('registration').get('success'))
        self.assertEqual(result.get('data').get('registration').get('message'), 'no_valid_license')

    @patch.object(HepClient, 'customer_activate', return_value="Response")
    @patch.object(HepClient, 'customers_by_id', return_value=INVALID_KEY_ME)
    @patch.object(HepClient, 'fetch_admin_token', return_value=b'"AABBCCDDEE**44566"')
    def test_user_cannot_register_with_invalid_key(self, admin_mock, confirmation_mock, id_mock):

        result = self.make_register_mutation('CONFIRMATION_KEY', 1)

        self.assertFalse(result.get('data').get('registration').get('success'))
        self.assertEqual(result.get('data').get('registration').get('message'), 'invalid_key')

    @patch.object(HepClient, '_customer_orders', return_value=VALID_TEACHERS_ORDERS)
    @patch.object(HepClient, 'customer_activate', return_value="Response")
    @patch.object(HepClient, 'customers_by_id', return_value=ME_DATA)
    @patch.object(HepClient, 'fetch_admin_token', return_value=b'"AABBCCDDEE**44566"')
    def test_teacher_can_register_with_remote_license(self, admin_mock, id_mock, activate_mock, orders_mock):
        result = self.make_register_mutation('CONFIRMATION_KEY', 1)

        user = User.objects.get(email=ME_DATA['email'])

        user_role_key = user.user_roles.get(user=user).role.key
        self.assertEqual(user_role_key, Role.objects.TEACHER_KEY)

        license = License.objects.get(licensee=user)
        self.assertEqual(license.for_role.key, Role.objects.TEACHER_KEY)

        school_class = SchoolClass.objects.get(users__in=[user])
        self.assertIsNotNone(school_class)

        self.assertTrue(result.get('data').get('registration').get('success'))
        self.assertTrue(user.is_authenticated)
