#!/usr/share/ucs-test/runner python3
## -*- coding: utf-8 -*-
## desc: tests the team related API calls, return values and exception handling.
## tags: [apptest, integrationtest]
## exposure: dangerous
## packages:
##   - univention-office365
## versions:
##  4.4-4: skip

####
# Skip here: This tests the graph api calls directly, but we currently
# do not support creating users through graph - as it is done in setUp()
####


import os
import logging
import argparse
import unittest
import time

import univention.testing.ucr as testing_ucr

from univention.office365.api.graph import Graph
from univention.office365.api.responseparser.create_team import get_team_id
from univention.office365.api.exceptions import GraphError
from helpers.random_strings import create_random_string_with_prefix


class Test_TeamsAPI(unittest.TestCase):

    def setUp(self):

        # the alias has to be one, which has the correct permissions assigned
        # to it. The owner is a user, which has the permission to create
        # teams, that means assignedPlan has "service": "TeamspaceAPI" to it.
        self.alias = 'o365domain'

        self.ucr = testing_ucr.UCSTestConfigRegistry()
        self.ucr.load()
        self.logger = logging.getLogger()

        # whenever we create a user, group or team, we want to delete it after
        # the test execution again. For the tearDown method we will store
        # a list of created users in the following List:
        self.test_users = []
        self.test_groups = []
        self.test_teams = []

        self.graph = None
        self.logger.debug("Loading Graph with alias '{alias}'...".format(
            alias=self.alias)
        )
        self.graph = Graph(
            ucr=self.ucr,
            name=__name__,
            connection_alias=self.alias
        )
        self.assertIsNotNone(self.graph, msg="Graph class was not loaded.")

        self.owner = self._create_random_user().get('id')

    def tearDown(self):
        for user in self.test_users:
            try:
                self.graph.delete_user(user)
            except GraphError:
                self.logger.warning("unable to delete user with id {}".format(user))
                pass
        for group in self.test_groups:
            try:
                self.graph.delete_team(group)
            except GraphError:
                self.logger.warning("unable to delete group with id {}".format(group))
                pass
        for team in self.test_teams:
            try:
                self.graph.delete_team(team)
            except GraphError:
                self.logger.warning("unable to delete team with id {}".format(team))
                pass
        self.graph.delete_user(self.owner)

    def _create_random_user(self):
        '''
        NOTE: the mailaddr must have the correct domain or an error says
        'You must use one of the verified domain names in your organization.'
        '''
        username = create_random_string_with_prefix(5, "testuser")
        password = '123' + create_random_string_with_prefix(8) + '@#$'
        mailaddr = create_random_string_with_prefix(8) + '@office365.dev-univention.de'
        new_user = self.graph.add_user(username, mailaddr, password)

        # store the users id for later in the tearDown of the test to be able
        # to delete it again...
        self.test_users.append(new_user['id'])

        return new_user

    def _wait_for_microsoft(self, timeout=10):
        time.sleep(timeout)  # this is bad

    def _create_sample_team(self, name=None):
        if name is None:
            name = create_random_string_with_prefix(20)
        # we can't use create_team because the owner needs a valid license for MS Teams
        # instead use create_team_from_group
        g = self.graph.create_group(name)
        group_id = g.get('objectId')
        for i in range(15):
            try:
                self.graph.add_group_owner(group_id, self.owner)
                break
            except GraphError:
                if i == 14:
                    raise
                time.sleep(3)
        team = None
        for i in range(15):
            try:
                team = self.graph.create_team_from_group(group_id)
                break
            except GraphError:
                if i == 14:
                    raise
                time.sleep(3)
        # parse the team_id out of the request (this is inconsistent in teams
        # API that with other API calls against graph, where the return value
        # is a JSON)
        team_id = get_team_id(team)
        # store team_id to be able to delete it later in tearDown
        self.test_teams.append(team_id)
        # wait for team to be usable
        for i in range(30):
            try:
                self.graph.get_team(team_id)
                break
            except GraphError:
                time.sleep(2)
        return team_id

    def test_create_team(self):
        team_id = self._create_sample_team()
        self.assertIsNotNone(
            team_id,
            'Created a team, but the returned json object did not have'
            ' a `Location` field to it, which we expected it to have.')

    def test_create_team_with_no_owner(self):
        ''' No exception occured when creating a team with a name but no owner '''
        with self.assertRaises(GraphError):
            self.graph.create_team(create_random_string_with_prefix(20), "")

    def test_create_team_with_no_name_and_owner(self):
        ''' We got no exception, even though created a team without a name '''
        with self.assertRaises(GraphError):
            self.graph.create_team("", "")

    def test_create_team_with_missing_parameters(self):
        '''
        We got no exception, although we created a team with `None` as its'
        team name.
        '''
        with self.assertRaises(GraphError):
            self.graph.create_team(None, None)

    def test_get_team(self):
        new_team = self._create_sample_team()
        retval = self.graph.get_team(new_team)
        self.assertIsNotNone(
            retval,
            'A new team was created. The call is expected to return a json'
            ' object to represent the newly created team. This object however'
            ' does not have the team name to it.')

    def test_add_team_member(self):
        team_id = self._create_sample_team()
        new_user = self._create_random_user()
        response = self.graph.add_team_member(
            team_id,
            new_user['id']
        )
        self.assertEqual(
            new_user['displayName'],
            response['displayName']
        )

    def test_list_team_members(self):
        new_user = self._create_random_user()
        team_id = self._create_sample_team()
        self._wait_for_microsoft(timeout=60)
        self.graph.add_team_member(team_id, new_user['id'])
        self._wait_for_microsoft(timeout=120)
        team_members = self.graph.list_team_members(team_id)
        self.assertIn('value', team_members)
        self.assertGreater(team_members['value'], 0)
        member_ids = map(lambda x: x['userId'], team_members['value'])
        self.assertTrue(
            new_user['id'] in member_ids,
            'A new user and a new team was created. The user has been added to'
            ' the team, the teams members have been listed and we expected to'
            ' a single element in the list of team members. But the element did'
            ' not have the users id to it. That is caused this assertion error.'
            ' assertion: {user_id} & {members}'.format(
                user_id=new_user['id'],
                members=member_ids
            ))

    def test_delete_team_member(self):
        new_user = self._create_random_user()
        team_id = self._create_sample_team()
        team_member_object = self.graph.add_team_member(team_id, new_user['id'])
        team_member_id = team_member_object['id']
        self.graph.delete_team_member(team_id, team_member_id)

    def test_create_team_from_group_with_invalid_id(self):
        '''
        We tried to create a team from an invalid group id and that worked for
        some reason. But we assumed it to raise an exception.
        '''
        with self.assertRaises(GraphError):
            self.graph.create_team_from_group(create_random_string_with_prefix(20))

    def test_delete_team(self):
        team_id = self._create_sample_team()
        self.graph.delete_team(team_id)

    def test_list_teams(self):
        team_id = self._create_sample_team()
        teams = self.graph.list_teams()
        for i in teams.get('value'):
            if i.get('id') == team_id:
                return
        self.assertTrue(False, 'team {} not found in list_teams()'.format(team_id))


if __name__ == '__main__':
    parser = argparse.ArgumentParser(
        description="Test for the Microsoft Graph API library integration",
    )
    parser.add_argument(
        '--fast',
        help='fail fast (exit after the first failed test)',
        action="store_false"
    )
    parser.add_argument(
        '-l',
        '--log',
        help='log file path',
        nargs='?',
        default='/tmp/test-{pid}.log'.format(
            pid=os.getpid()
        )
    )

    args = parser.parse_args()

    logging.basicConfig(
        level=logging.DEBUG,
        filename=args.log,
        filemode='w')

    unittest.main(failfast=args.fast)

# vim: filetype=python expandtab tabstop=4 shiftwidth=4 softtabstop=4
