#!/usr/share/ucs-test/runner python3
## -*- coding: utf-8 -*-
## desc: change team owner in azure
## tags: [apptest]
## exposure: dangerous
## packages:
##   - univention-office365

"""
This test is used to check the team owner change in Azure.
- Use o365domain connection
- set the UCR variable office365/groups/sync=yes
- Create user1 in UDM
- Create user2 in UDM
- Create group in UDM with UniventionMicrosoft365Team=1 and UniventionMicrosoft365GroupOwners=user_dn
- Check the creation of the team in Azure (It's using the wait_for_seconds decorator to wait for the team to be created up to 500 seconds)
- check team owner in Azure
- change team owner to user2_dn in UDM
- check team owner in Azure
"""
import univention.testing.utils as utils
import univention.testing.ucr as ucr_test
import univention.testing.udm as udm_test
from univention.config_registry import handler_set

import helpers.office365_test_helpers as o365helpers
from univention.office365.microsoft.account import AzureAccount
from univention.office365.microsoft.core import MSGraphApiCore

with utils.AutomaticListenerRestart():
	with udm_test.UCSTestUDM() as udm:
		with ucr_test.UCSTestConfigRegistry() as ucr:
			ucr.load()

			alias = 'o365domain'

			core = MSGraphApiCore(AzureAccount(alias))

			handler_set(["office365/groups/sync=yes"])
			utils.restart_listener()

			print("*** Creating members ***")
			user_dn, username = o365helpers.create_team_member(udm, ucr, alias)
			user2_dn, username2 = o365helpers.create_team_member(udm, ucr, alias)

			print("*** Creating Team ***")
			group_dn, group_name = o365helpers.create_team(udm, ucr, owner_dn=user_dn, users=[user_dn])

			created_team = o365helpers.check_team_created(core, group_name)

			team_id = created_team.id
			owner = o365helpers.check_team_owner(core, team_id, username)

			print("*** Change owner ***")
			udm.modify_object(modulename="groups/group", dn=group_dn, set=dict(
				UniventionMicrosoft365Team=1,
				UniventionMicrosoft365GroupOwners=user2_dn,))

			owner = o365helpers.check_team_owner(core, team_id, username2)
			print("*** All went well.")